why C clock() returns 0
The right way of using clock() to measure time would be:
printf("\nTime elapsed: %.2f\n",1.0*(end-start)/CLOCKS_PER_SEC);
This is because clock_t isn't guaranteed to be an int, or any other type for that matter.
Well, do you want the time something_else()
takes? Try this:
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
int main(void) {
struct timeval start, end;
long mtime, secs, usecs;
gettimeofday(&start, NULL);
something_else();
gettimeofday(&end, NULL);
secs = end.tv_sec - start.tv_sec;
usecs = end.tv_usec - start.tv_usec;
mtime = ((secs) * 1000 + usecs/1000.0) + 0.5;
printf("Elapsed time: %ld millisecs\n", mtime);
return 0;
}
I guess the reason is that your something_else()
consumes so little time that exceed the precision of clock()
. I tried calling clock()
twice consequently and both start
and end
is zero, but result is reasonable when I do some time-consuming stuff between.
Here is my test code snippet:
int main(void) {
clock_t start, end;
start = clock();
int c;
for (int i = 0; i < 100; i++) {
for (int j = 0; j < (1<<30); j++) {
c++;
}
}
end = clock();
printf("start = %d, end = %d\n", start, end);
return 0;
}
And the result on my computer is:
start = 0, end = 27700000
Also, two tips:
- When testing, do not use any compiler optimization. You may think your
something_else()
is time-consuming but the compiler may just ignore those operations (especially loops) since it think them as meaningless. - Use
sizeof(clock_t)
on your platform to see the size ofclock_t
.
clock
function does not measure CPU clock cycles.
C says clock
"returns the implementation’s best approximation to the processor
time used by the program since the beginning of an implementation-defined era related
only to the program invocation."
If between two successive clock
calls you program takes less time than one unity of the clock
function, you could get 0
.
POSIX clock
defines the unity with CLOCKS_PER_SEC
as 1000000 (unity is then 1 microsecond).
http://pubs.opengroup.org/onlinepubs/009604499/functions/clock.html
To measure clock cycles in x86/x64 you can use inline assembly to retreive the clock count of the CPU Time Stamp Counter register rdtsc
.