clock()精度 [英] clock() accuracy

查看:176
本文介绍了clock()精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过很多关于使用clock()函数确定程序中经过的时间的帖子,代码看起来像这样:

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

//code to be timed
.
.
.

end_time = clock();
elapsed_time = (end_time - start_time) / CLOCKS_PER_SEC;

CLOCKS_PER_SEC的值几乎肯定不是每秒的实际时钟滴答数,所以我有点对结果保持警惕。不用担心线程和I / O,clock()函数的输出是否以某种方式缩放,以便该分度产生正确的挂钟时间?

The value of CLOCKS_PER_SEC is almost surely not the actual number of clock ticks per second so I am a bit wary of the result. Without worrying about threading and I/O, is the output of the clock() function being scaled in some way so that this divison produces the correct wall clock time?

推荐答案

您的问题的答案是肯定的。

The answer to your question is yes.

clock() case是指挂钟而不是CPU时钟,因此乍一看可能会引起误解。对于我所见过的所有机器和编译器,它返回的时间以毫秒为单位,因为我从未见过 CLOCKS_PER_SEC 不为1000的情况。因此, clock()以毫秒为单位,准确度通常会略低。

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.

如果您对实际周期,这可能很难获得。
rdtsc 指令使您可以从启动CPU以来访问数字伪循环。在较旧的系统(例如Intel Core 2)上,此数字通常与实际CPU频率相同。

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.

要获得比 clock()更准确的计时器,您可以将需要使用特定于操作系统的硬件性能计数器。这些是使用上一段的 rdtsc指令在内部实现的。

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.

这篇关于clock()精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆