简体   繁体   中英

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: %f\n", 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?

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.

clock measures CPU time (in Linux at least). A sleeping process consumes no CPU time.

If you want to measure a time interval as if with a stopwatch, regardless of what your process is doing, use clock_gettime with CLOCK_MONOTONIC .

man clock() has the answer:

The clock() function returns an approximation of processor time used by the program.

Which clearly tells that clock() returns the processor time used by the program, not what you were expecting the total run time of the program which is typically done using gettimeofday .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM