clock() accuracy

前端 未结 1 563
野趣味
野趣味 2021-01-23 11:07

I have seen many posts about using the clock() function to determine the amount of elapsed time in a program with code looking something like:

start_time = clock         


        
相关标签:
1条回答
  • 2021-01-23 11:11

    The answer to your question is yes.

    clock() in this case refers to a wallclock rather than a CPU clock so it could be misleading at first glance. For all the machines and compilers I've seen, it returns the time in milliseconds since I've never seen a case where CLOCKS_PER_SEC isn't 1000. So the precision of clock() is limited to milliseconds and the accuracy is usually slightly less.

    If you're interested in the actual cycles, this can be hard to obtain. The rdtsc instruction will let you access the number "pseudo"-cycles from when the CPU was booted. On older systems (like Intel Core 2), this number is usually the same as the actual CPU frequency. But on newer systems, it isn't.

    To get a more accurate timer than clock(), you will need to use the hardware performance counters - which is specific to the OS. These are internally implemented using the 'rdtsc' instruction from the last paragraph.

    0 讨论(0)
提交回复
热议问题