Suugaku Suugaku - 8 months ago 66
C Question

C: using clock() to measure time in multi-threaded programs

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 ?

caf caf
Answer Source

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 in time.h. The CLOCK_MONOTONIC clock in particular is the best to use for this:

struct timespec start, finish;
double elapsed;

clock_gettime(CLOCK_MONOTONIC, &start);

/* ... */

clock_gettime(CLOCK_MONOTONIC, &finish);

elapsed = (finish.tv_sec - start.tv_sec);
elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;

(Note that I have done the calculation of elapsed carefully 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 with sysconf(_SC_MONOTONIC_CLOCK)), then you can use CLOCK_REALTIME as 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.