I've got something like this:
clock_t start, end;
start=clock();
something_else();
end=clock();
printf("\nClock cycles are: %d - %d\n",start,end);
and I always get as an output "Clock cycles are: 0 - 0"
Any idea why this happens?
(Just to give little detail, the something_else() function performs a left-to-right exponentiation using montgomery representation, moreover I don't know for certain that the something_else() function does indeed take some not negligible time.)
This is on Linux. The result of uname -a is:
Linux snowy.*****.ac.uk 2.6.32-71.el6.x86_64 #1 SMP Fri May 20 03:51:51 BST 2011 x86_64 x86_64 x86_64 GNU/Linux
The right way of using clock() to measure time would be:
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: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 theclock
function, you could get0
.POSIX
clock
defines the unity withCLOCKS_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
.I have used the little program below to investigate wall clock time and CPU time.
On my test sytem this prints
CLOCKS_PER_SEC 1000000
CPU time usage resolutio
n looks to be0.010000 seconds
gettimeofday changed by
9634 uS
when CPU time changed by0.010000
gettimeofday resolution looks to be 1 us
Check the value of
CLOCKS_PER_SEC
intime.h/clock.h
. On my system, for example, ( Dev Cpp on Windows 7 ) its a mere1000
. So as far as my program is concerned, there are 1000 ticks per second. Yoursomething_else
would be executed in a matter of microseconds. And henceclock()
returns zero both before and after the function call.On my system, when I replace your
something_else
with a time consuming routine like thisI get
On one of linux boxes, I find the following in
bits/time.h
So do consider this before analyzing the return value of
clock()
I guess the reason is that your
something_else()
consumes so little time that exceed the precision ofclock()
. I tried callingclock()
twice consequently and bothstart
andend
is zero, but result is reasonable when I do some time-consuming stuff between.Here is my test code snippet:
And the result on my computer is:
Also, two tips:
something_else()
is time-consuming but the compiler may just ignore those operations (especially loops) since it think them as meaningless.sizeof(clock_t)
on your platform to see the size ofclock_t
.