I am trying to understand the clock_t clock(void);
function better and have following question:
Did I understand that correctly that clock
measures the number of ticks of a process since it is actively running and sleep
suspends the calling thread – in this case there is only one thread, namely the main-thread – and therefore suspends the whole process. Which means that clock
does not measure the cpu-time (ticks) of the process, since it is not actively running?
If so what is the recommended way to measure the actual needed time?
"The clock()
function returns an approximation of processor time used by the program." Source
"The CPU time (process time) is measured in clock ticks or seconds." Source
"The number of clock ticks per second can be obtained using: sysconf(_SC_CLK_TCK);
" Source
#include <stdio.h> // printf
#include <time.h> // clock
#include <unistd.h> // sleep
int main()
{
printf("ticks per second: %zu\n", sysconf(_SC_CLK_TCK));
clock_t ticks_since_process_startup_1 = clock();
sleep(1);
clock_t ticks_since_process_startup_2 = clock();
printf("ticks_probe_1: %zu\n", ticks_since_process_startup_1);
printf("sleep(1);\n");
printf("ticks_probe_2: %zu\n", ticks_since_process_startup_2);
printf("ticks diff: %zu <-- should be 100\n", ticks_since_process_startup_2 - ticks_since_process_startup_1);
printf("ticks diff sec: %Lf <-- should be 1 second\n", (long double)(ticks_since_process_startup_2 - ticks_since_process_startup_1) / CLOCKS_PER_SEC);
return 0;
}
Resulting Output:
ticks per second: 100
ticks_probe_1: 603
sleep(1);
ticks_probe_2: 616
ticks diff: 13 <-- should be 100
ticks diff sec: 0.000013 <-- should be 1 second
Does
clock
measuresleep
i.e. suspended threads?
No.
(Well, it could measure it, there's nothing against it. You could have a very bad OS that implements sleep()
as a while (!time_to_sleep_expired()) {}
busy loop. But any self-respected OS will try to make the process not to use CPU when in sleep()
).
Which means that clock does not measure the cpu-time (ticks) of the process, since it is not actively running?
Yes.
If so what is the recommended way to measure the actual needed time?
To measure "real-time" use clock_gettime(CLOCK_MONOTONIC, ...)
on a POSIX system.
The number of clock ticks per second can be obtained using: sysconf(_SC_CLK_TCK);
Yes, but note that sysconf(_SC_CLK_TCK);
is not CLOCKS_PER_SECOND
. You do not use ex times()
in your function, you use clock()
, I do not really get why you print sysconf(_SC_CLK_TCK);
. Anyway, see for example sysconf(_SC_CLK_TCK) vs. CLOCKS_PER_SEC .