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

C

C Problem Overview


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 ?

C Solutions


Solution 1 - C

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

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 https://stackoverflow.com/questions/275004/c-timer-function-to-provide-time-in-nano-seconds

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSuugakuView Question on Stackoverflow
Solution 1 - CcafView Answer on Stackoverflow
Solution 2 - CManfreView Answer on Stackoverflow