基于c++11 的高精度计时器
个人博客 http://blog.kedixa.top
c++11 增加了用于处理时间的标准库<chrono>
,于是便可以很方便的实现一个程序计时器,用于测量某段代码执行所使用的时间。
timer.h
如下:
#ifndef TIMER_H_
#define TIMER_H_
#include<chrono>
#include<string>
namespace kedixa
{
class timer
{
typedef std::chrono::steady_clock::time_point tp;
typedef std::chrono::duration<double> dd;
typedef std::chrono::steady_clock sc;
private:
tp _begin;
dd _span;
public:
timer()
: _begin(tp()), _span(dd(0)){}
void start()
{
_begin = sc::now();
}
void pause()
{
tp _end = sc::now();
_span += std::chrono::duration_cast<dd>(_end - _begin);
}
void stop(std::string head = std::string(),
std::string tail = std::string())
{
tp _end = sc::now();
_span += std::chrono::duration_cast<dd>(_end - _begin);
std::cout << head << _span.count() << " seconds" << tail << std::endl;
_span = dd(0);
}
~timer()
{}
};
} // namespace
#endif // TIMER_H_
main.cpp
如下:
#include<iostream>
#include<string>
#include "timer.h"
using namespace std;
int main()
{
using kedixa::timer; // 使用命名空间
timer t; // 定义一个计时器
t.start(); // 开始计时
for(int i = 0; i < 1000000000; i++);
t.pause(); // 暂停计时
// do some other things
t.start(); // 开始计时
for(int i = 0; i < 1000000000; i++);
//结束计时并输出结果,两个参数表示额外内容,也可以省略参数
t.stop(string("It takes "), string("."));
return 0;
}
编译:
为了测试,不要加优化选项
g++ -std=c++11 main.cpp
可能的运行结果:
It takes 4.66544 seconds.
总结
处理时间的标准库为处理时间提供了很大的方便,实现一个简单的计时器可以很容易地测量代码执行的效率,再也不用四处去找奇怪的函数来测量效率了。 timer类的实现也浅显易懂,如果有不同的需求也很容易修改。