I’ve always used clock() to measure how much time my application took from start to finish, as;
int main(int argc, char *argv[]) {
const clock_t START = clock();
// ...
const double T_ELAPSED = (double)(clock() - START) / CLOCKS_PER_SEC;
}
Since I’ve started using POSIX threads this seem to fail. It looks like clock() increases N times faster with N threads. As I don’t know how many threads are going to be running simultaneously, this approach fails. So how can I measure how much time has passed ?
clock()measure the CPU time used by your process, not the wall-clock time. When you have multiple threads running simultaneously, you can obviously burn through CPU time much faster.If you want to know the wall-clock execution time, you need to use an appropriate function. The only one in ANSI C is
time(), which typically only has 1 second resolution.However, as you’ve said you’re using POSIX, that means you can use
clock_gettime(), defined intime.h. TheCLOCK_MONOTONICclock in particular is the best to use for this:(Note that I have done the calculation of
elapsedcarefully to ensure that precision is not lost when timing very short intervals).If your OS doesn’t provide
CLOCK_MONOTONIC(which you can check at runtime withsysconf(_SC_MONOTONIC_CLOCK)), then you can useCLOCK_REALTIMEas a fallback – but note that the latter has the disadvantage that it will generate incorrect results if the system time is changed while your process is running.