如何获取 C++ 中运行函数所用的时间
我通过谷歌搜索尝试了一些代码:
clock_t start, end;
start = clock();
//CODES GOES HERE
end = clock();
std::cout << end - start <<"\n";
std::cout << (double) (end-start)/ CLOCKS_PER_SEC;
但结果经过的时间始终为 0,即使
std::cout << (double) (end-start)/ (CLOCKS_PER_SEC/1000.0 );
不知道为什么,但当我在 Java 中得到类似的代码时: getCurrentTimeMillis() 它运行良好。我希望它显示毫秒,因为计算机的计算速度可能如此之快。
I tried some codes by googling :
clock_t start, end;
start = clock();
//CODES GOES HERE
end = clock();
std::cout << end - start <<"\n";
std::cout << (double) (end-start)/ CLOCKS_PER_SEC;
but the result elapsed time always was 0, even with
std::cout << (double) (end-start)/ (CLOCKS_PER_SEC/1000.0 );
Don't know why but when I get the similar in Java : getCurrentTimeMillis() it works well. I want it to show the milliseconds as maybe the computer compute so fast.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为不能保证
clock
具有足够高的分辨率来分析您的函数。如果你想知道一个函数执行的速度有多快,你应该运行它几千次而不是一次,测量它所花费的总时间并取平均值。I don't think it's guaranteed that
clock
has a high enough resolution to profile your function. If you want to know how fast a function executes, you should run it maybe a few thousands times instead of once, measure the total time it takes and take the average.这将打印出运行 main 所花费的时间。您可以将代码放在作用域中来对多个部分进行计时,即
{ boost::progress_timer timer; ... }
。This will print out the time it took to run main. You can place your code in scopes to time several parts, i.e.
{ boost::progress_timer timer; ... }
.这个问题在某种程度上与您的问题相似:Timing a function in a C++ program that running on Linux
看一下这个答案!
This question is somehow similar to yours: Timing a function in a C++ program that runs on Linux
Take a look at this answer!