Sunday, October 26, 2014

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
}
}

No comments:

Post a Comment