Sunday, October 26, 2014

Show longest continuous block of code not covered by tests

Usage: nocov.py
import fileinput
count = 0
lengths = {}
first = 0
for line in fileinput.input():
    if first and ('stm mis' in line or 'pln' in line):
        lengths[first] += 1
    else:
        t = line.split("id='t")
        if len(t) < 2:
            continue
        first = t[-1].split("'")[0]
        lengths[first] = 1

for x in sorted(lengths.items(), key=lambda (x, y): y):
    print x

Profiling C++ scopes

The following simple class measure time spent in scope it is declared in:
class profile {
    // usage: profile __profile(__FILE__, __LINE__);
    static map < pair, clock_t> __total;
    string _file;
    unsigned _line;
    clock_t _start;
public:
    profile(const char* file, unsigned line) :
        _file(file), _line(line), _start(clock()) {
    }
    ~profile() {
        clock_t d = clock() - _start;
        clock_t t = __total[make_pair(_file, _line)] += d;
        OutputDebugStringA(((string)_file + ':' + to_string(_line) + "+=" + to_string(d) + " = " + to_string(t) + '\n').c_str());
    }
};
map < pair, clock_t> profile::__total;
Example:
void foo() {
profile __profile(__FILE__, __LINE__); // measure time in foo
// other code
while (something) {
profile __profile(__FILE__, __LINE__); // measure time in while loop
}
}