Platform independent, crude timing of code

I work a lot on MacOS where I write code that I want to use on linux later. Unfortunately some of the normal timing functions are missing on MacOS. I don’t quite remember which. So I have some crude platform independent code for timing c++ code. I am aware it does not really count the CPU usage, but putting it around code you want to time you can still get a feeling for how much time is spent in that part of your code.


class pTimer {
 timeval t1, t2;

public:
 double t;
 pTimer(): t(0){};
 void start() {gettimeofday(&t1, NULL);};
 void stop() {gettimeofday(&t2, NULL);
 t +=
 (t2.tv_sec -
 t1.tv_sec) * 1000.0 + (t2.tv_usec - t1.tv_usec) / 1000.0;};
 void reset() {t=0;};
 void restart() {t=0;gettimeofday(&t1, NULL);};
};

it is used like this:


pTimer t1;
t1.start();
<computationally intensive part of the code>
t1.stop();
printf("took %f miliseconds", t1.t);

restart(); sets the timer to zero and starts it at the same time, using start(); again will add to the time already on the counter (useful if you want to accumulate time from different parts of your source in one timer).

Leave a Reply

Your email address will not be published. Required fields are marked *

seven + 3 =