C: using clock() to measure time in multi-threaded programs
Solution 1:
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.
Solution 2:
What timing resolution do you need? You could use time() from time.h for second resolution. If you need higher resolution, then you could use something more system specific. See Timer function to provide time in nano seconds using C++