Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

linux - why C clock() returns 0

I've got something like this:

clock_t start, end;
start=clock();

something_else();

end=clock();
printf("
Clock cycles are: %d - %d
",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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...