C中最好的计时方法?
以高分辨率和可移植性对代码部分进行计时的最佳方法是什么?
/* Time from here */
ProcessIntenseFunction();
/* to here. */
printf("Time taken %d seconds %d milliseconds", sec, msec);
是否有一个标准库可以提供跨平台解决方案?
What is the best way to time a code section with high resolution and portability?
/* Time from here */
ProcessIntenseFunction();
/* to here. */
printf("Time taken %d seconds %d milliseconds", sec, msec);
Is there a standard library that would have a cross-platform solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我认为这应该有效:
I think this should work:
gettimeofday() 可能会做你想做的事。
如果您使用的是 Intel 硬件,以下是读取 CPU 实时指令计数器的方法。 它会告诉您自处理器启动以来执行的 CPU 周期数。 这可能是您可以用于性能测量的最细粒度、最低开销的计数器。
请注意,这是 CPU 周期数。 在 Linux 上,您可以从 /proc/cpuinfo 获取 CPU 速度并除以秒数。 将其转换为双精度型非常方便。
当我在我的盒子上运行它时,我得到
Here's the 英特尔开发人员指南这提供了大量的细节。
gettimeofday() will probably do what you want.
If you're on Intel hardware, here's how to read the CPU real-time instruction counter. It will tell you the number of CPU cycles executed since the processor was booted. This is probably the finest-grained, lowest overhead counter you can get for performance measurement.
Note that this is the number of CPU cycles. On linux you can get the CPU speed from /proc/cpuinfo and divide to get the number of seconds. Converting this to a double is quite handy.
When I run this on my box, I get
Here's the Intel developer's guide that gives tons of detail.
gettimeofday 将返回系统时钟分辨率内精确到微秒的时间。 您可能还想查看 SourceForge 上的高分辨率计时器项目。
gettimeofday will return time accurate to microseconds within the resolution of the system clock. You might also want to check out the High Res Timers project on SourceForge.
如果您不需要 CPU 时间,那么我认为您正在寻找的是 timeval 结构。
我使用以下方法来计算执行时间:
If you don't want CPU time then I think what you're looking for is the timeval struct.
I use the below for calculating execution time:
我使用 SDL_GetTicks 。 libsdl.org/" rel="nofollow noreferrer">SDL 库。
I use SDL_GetTicks from the SDL library.
高分辨率是相对的...
我正在查看这些示例,它们大多迎合毫秒。
然而对我来说,测量微秒很重要。
我还没有看到微秒级的独立于平台的解决方案,并且认为像下面的代码这样的东西会很有用。
我暂时只在 Windows 上进行计时,并且在 AIX/Linux 上执行相同操作时很可能会添加 gettimeofday() 实现。
用法:
High resolution is relative...
I was looking at the examples and they mostly cater for milliseconds.
However for me it is important to measure microseconds.
I have not seen a platform independant solution for microseconds and thought something like the code below will be usefull.
I was timing on windows only for the time being and will most likely add a gettimeofday() implementation when doing the same on AIX/Linux.
Usage: