-2

To the guys whom marked my question as answered/duplicate: Those solutions in the given link cannot calculate the CPU time in a multi-thread program in Linux.

I am using the following code to find the execution time of my code. It works perfectly on my Windows 10 machine but when it comes to Linux, I get incorrect execution time (for example the real execution time is less than 2 seconds but the code prints 10 seconds). I have tried both GCC and Intel compilers but still have the same issue. Any idea what is wrong? Thank you for your time and help.

clock_t begin;
clock_t end;
double time_spent;

begin = clock();
// run some calculations //
end = clock();
time_spent = ((double)(end - begin)) / CLOCKS_PER_SEC;
printf("Elapsed: %.12f \n\n", time_spent);
Ash
  • 117
  • 11

1 Answers1

1

Read carefully the man pages of clock(3) and of time(7) (and perhaps also of clock_gettime(2), which probably is used to implement clock). The clock documentation explains:

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

(emphasis is mine)

Use also time(1) to measure the time of your program.

Notice that clock function is measuring the CPU time, not the real wall-clock time.

It is actually rumored that on Windows, clock is incorrectly measuring the real wall-clock time. But the standard clock function should indeed give processor time (check n1570, the C11 standard, §7.27.2.1 for more).

For example, if your long-going calculation is doing some I/O (and that is often the case), it might wait for the disk (or for output to the terminal emulator, or input from the user), and then the CPU time and the real wall-clock time are very different.

I get incorrect execution time (for example the real execution time is less than 2 seconds but the code prints 10 seconds).

If your program is multi-threaded, it might have a processor time (accumulated on several cores) which is bigger than the real wall-clock time.

I have tried both GCC and Intel compilers but still have the same issue.

The clock function is provided by your C standard library. The standard <time.h> header is just declaring it. Your libc.so.6, probably from GNU glibc (but you might also try musl-libc), is implementing it. So you should expect that changing compilers won't change the behavior of clock.

Any idea what is wrong?

Perhaps your expectations are wrong (but without an MCVE we cannot be sure).

You comment also:

I was not able to find a simple way to get CPU time in my program.

Consider then using clock_gettime(2) with one of

   CLOCK_PROCESS_CPUTIME_ID (since Linux 2.6.12)
          Per-process CPU-time clock (measures CPU time consumed by all
          threads in the process).

   CLOCK_THREAD_CPUTIME_ID (since Linux 2.6.12)
          Thread-specific CPU-time clock.
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547