2012-10-02 46 views
0

我想的是一样的东西:C++:运行一个量的算法的时间(不计时)

// Runs algorithm() n times during an amount of seconds. 
void run(int seconds) { 
    clock_t start = clock(); 
    clock_t current = start; 
    while(double (current - start)/CLOCKS_PER_SEC <= seconds) { 
    algorithm(); 
    current = clock(); 
    } 
} 

我选择了clock()time()避免会计时间进程睡眠。 我想知道是否有更好的方法来实现这一点,而不使用chrono

+0

您可以使用更高精度的特定于平台的工具,例如QueryPerformanceCounter,或者使用[Boost's Timers]进行实验(http://www.boost.org/doc/libs/1_51_0/libs/timer/doc/) index.html),但我不知道底层实现是否更好。 – chris

+0

您是否想要便携式解决方案或平台特定的解决方案? –

+0

为什么有人想避免'std :: chrono'? – bames53

回答

2

STLSoft有一个performance_counter可在UNIX和Windows平台上工作。图书馆只是头,只需要一个简单的包括:

#include <platformstl/performance/performance_counter.hpp> 

void run(int seconds) { 
    platformstl::performance_counter pc; 
    platformstl::performance_counter::interval_type current = 0; 
    pc.start(); 
    while ((current/1000) <= seconds){ 
    algorithm(); 
    current += pc.stop_get_milliseconds_and_restart(); 
    } 
} 

你也可以看看自己的提示来源。