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.