2010-11-05 95 views
7

所以我读这boost docs但我仍然不知道怎样做这样简单的事升压计时器:当我需要时如何获得时间?

int main() { 
    //stuff 
    startTimer(); 
    // do stuff 
    int i =getTimerValue(); 
    //stuff 
} 

所以要得到我所做的东西执行时间。如何做这样的事情?

+0

我不知道我理解。您想要检索自上次重新启动计时器以来的时间? – 2010-11-05 12:03:57

回答

19

使用boost::timer

#include <boost/timer.hpp> 
int main() { 
    boost::timer t; // start timing 
    ... 
    double elapsed_time = t.elapsed(); 
    ... 
} 

注意一个boost::progress_timer的destuctor将显示时间。因此,如果您的目标只是显示函数中间过去的时间,请使用范围。

int main() { 
    { 
    boost::progress_timer t; // start timing 
    ... 
    } // elapsed time displayed here when t is destructed 
    ... 
} 
+0

尽管你的第一部分代码回答了这个问题,'boost :: timer'并不显示销毁时间,因此你的答案的后半部分是不正确的。为此,您需要'boost :: progress_timer',如下面的Steve所述。见[docs](http://www.boost.org/doc/libs/1_47_0/libs/timer/timer.htm) – Arth 2013-04-27 21:00:12

+0

@Arth fixed ... – log0 2013-09-16 09:12:07

5

#include <boost/progress.hpp> 
void function() 
{ 
    progress_timer t; // start timing 
    // do stuff 
    return 0; 
} 

更换这一点,你会得到你想要什么,而不是使用printf虽然。

定时器开始施工并显示销毁(即在fn出口处)。这是一种典型的在C++中执行作用域任务(时序,锁定等)的方式。

+0

这就是我的观点 - 当函数结束时不返回时间值,直到部分函数停止工作时才显示时间值。 – Rella 2010-11-05 12:24:57

+0

@Kabumbus:在这种情况下,使用''。 – 2010-11-05 12:27:08

0

根据上述特征,还有以下想法,即经历时间由析构函数显示。

#include "boost/timer/timer.hpp" 
int main() 
{ 
    // ... 
    boost::timer:auto_cpu_timer *boost_timer = new boost::timer:auto_cpu_timer(); 
    // we want to measure the time of execution of this part of code 
    // ... 
    delete boost_timer; // show the elapsed time 
    // then we can repeat 
    boost_timer = new boost::timer:auto_cpu_timer(); 
    // ... 
    delete boost_timer; 
    // ... 
}