Skip to content
Advertisement

Measuring execution time with clock in sec in C not working

I’m trying to measure execution time in C using clock() under linux using the following:

#include <time.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char const* argv[])
{
  clock_t begin, end;
  begin = clock();
  sleep(2);
  end = clock();
  double spent = ((double)(end-begin)) / CLOCKS_PER_SEC;
  printf("%ld %ld, spent: %fn", begin, end, spent);
  return 0;
}

The output is:

1254 1296, spent: 0.000042

The documentation says to divide the clock time by CLOCKS_PER_SEC to get the execution time in sec, but this seems pretty incorrect for a 2sec sleep.

What’s the problem?

Advertisement

Answer

Sleeping takes almost no execution time. The program just has to schedule its wakeup and then put itself to sleep. While it’s asleep, it is not executing. When it’s woken up, it doesn’t have to do anything at all. That all takes a very tiny fraction of a second.

It doesn’t take more execution time to sleep longer. So the fact that there’s a 2 second period when the program is not executing has no effect.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement