why C clock() returns 0

后端 未结 7 1381
自闭症患者
自闭症患者 2020-11-30 12:48

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);
         


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 13:08

    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.

提交回复
热议问题