测试代码运行时间是一个很常用的需求,下面写好了一个模板,直接调用就行:
#include <chrono> // for std::chrono functions
class Timer
{
private:
// Type aliases to make accessing nested type easier
using clock_t = std::chrono::high_resolution_clock;
using second_t = std::chrono::duration<double, std::ratio<1> >;
std::chrono::time_point<clock_t> m_beg;
public:
Timer() : m_beg(clock_t::now())
{
}
void reset()
{
m_beg = clock_t::now();
}
double elapsed() const
{
return std::chrono::duration_cast<second_t>(clock_t::now() - m_beg).count();
}
};
使用方法:
int main()
{
Timer t; //记录初始时间
// Code to time goes here
std::cout << "Time elapsed: " << t.elapsed() << " seconds\n";
return 0;
}
需要注意事项为:
- 要使用release版本,而不是debug,这两个时间差距会很大
- 要确保没有其他占用内存或者cpu的进城,比如游戏等。
- 多测几次,确保每次结果都接近,然后取平均值。