开发者

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

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 a开发者_JAVA技巧s maybe the computer compute so fast.


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.


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


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

Take a look at this answer!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜