代码的高分辨率计时部分
我想测量循环内函数的速度。 但为什么我的做法总是打印“0”而不是具有 9 位小数精度(即纳秒/微秒)的高分辨率计时?
正确的做法是什么?
#include <iomanip>
#include <iostream>
#include <time.h>
int main() {
for (int i = 0; i <100; i++) {
std::clock_t startTime = std::clock();
// a very fast function in the middle
cout << "Time: " << setprecision(9) << (clock() - startTime + 0.00)/CLOCKS_PER_SEC << endl;
}
return 0;
}
相关问题:
I want to measure the speed of a function within a loop. But why my way of doing it always print "0" instead of high-res timing with 9 digits decimal precision (i.e. in nano/micro seconds)?
What's the correct way to do it?
#include <iomanip>
#include <iostream>
#include <time.h>
int main() {
for (int i = 0; i <100; i++) {
std::clock_t startTime = std::clock();
// a very fast function in the middle
cout << "Time: " << setprecision(9) << (clock() - startTime + 0.00)/CLOCKS_PER_SEC << endl;
}
return 0;
}
Related Questions:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
将时间计算函数移到
for () { .. }
语句之外,然后将总执行时间除以测试循环中的操作数。注意:std::clock() 缺乏足够的精度来进行分析。 参考。
Move your time calculation functions outside
for () { .. }
statement then devide total execution time by the number of operations in your testing loop.Note: std::clock() lacks sufficient precision for profiling. Reference.
一些提示:
A few pointers:
如果您需要更高的分辨率,唯一的方法是依赖于平台。
在 Windows 上,请查看 QueryPerformanceCounter/QueryPerformanceFrequency API。
在 Linux 上,查找 clock_gettime()。
If you need higher resolution, the only way to go is platform dependent.
On Windows, check out the QueryPerformanceCounter/QueryPerformanceFrequency API's.
On Linux, look up clock_gettime().
请参阅我就同一件事提出的问题:显然
clock()
的分辨率不能保证如此高。C++ 在 Linux 上获取毫秒时间 --clock() 似乎无法正常工作
尝试
gettimeofday
函数,或 boostSee a question I asked about the same thing: apparently
clock()
's resolution is not guaranteed to be so high.C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly
Try
gettimeofday
function, or boost如果您需要平台独立性,则需要使用 ACE_High_Res_Timer (http://www.dre.vanderbilt.edu/Doxygen/5.6.8/html/ace/a00244.html)
If you need platform independence you need to use something like ACE_High_Res_Timer (http://www.dre.vanderbilt.edu/Doxygen/5.6.8/html/ace/a00244.html)
您可能想考虑使用 openMp。
You might want to look into using openMp.