How to get the time elapsed running a function in C++

白昼怎懂夜的黑 提交于 2020-01-05 04:31:05

问题


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.


回答1:


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.




回答2:


#include <boost/progress.hpp>

int main()
{
    boost::progress_timer timer;
    // code to time goes here
}

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; ... }.




回答3:


This question is somehow similar to yours: Timing a function in a C++ program that runs on Linux

Take a look at this answer!



来源:https://stackoverflow.com/questions/5283031/how-to-get-the-time-elapsed-running-a-function-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!