精确测试执行一个函数所需时间
c++11 新增了 std::chrono library
库
包含了三种时钟
system_clock
系统时钟steady_clock
稳定时钟 (单调时钟) 绝不会调整的high_resolution_clock
高分辨率时钟
三种结构体的主要参数
//部分源码
/**
* @brief System clock.
*
* Time returned represents wall time from the system-wide clock.
*/
struct system_clock
{
typedef chrono::nanoseconds duration; //纳秒
typedef duration::rep rep; //时钟类型
typedef duration::period period; //时钟周期
typedef chrono::time_point<system_clock, duration> time_point;//时间点
};
/**
* @brief Monotonic clock
*
* Time returned has the property of only increasing at a uniform rate.
*/
struct steady_clock
{
typedef chrono::nanoseconds duration;
typedef duration::rep rep;
typedef duration::period period;
typedef chrono::time_point<steady_clock, duration> time_point;
};
/**
* @brief Highest-resolution clock
*
* This is the clock "with the shortest tick period." Alias to
* std::system_clock until higher-than-nanosecond definitions
* become feasible.
*/
using high_resolution_clock = system_clock;
/*类似上一句*/
typedef system_clock high_resolution_clock;
要想精确的计算出一个函数的运行时间.所选的时钟就不能因为部分外部因素影响(例如人为修改系统时间,或者修改硬件时钟)
当我们需要知道一个函数的执行时间的时候,只需要记录2个时间点.
例如startRunTime 和 endTime只需要记录2个时间点的差值就可以算来。
steady_clock 使用的是系统的单调时间,即从某个时间点开始到未来的时间。用户不能修改这个时间, 严格来说这个获取的 jiffies的值(为自操作系统启动以来的时钟滴答的数目)
#include <iostream>
#include <chrono>
using namespace std;
class StopWatch {
public:
typedef std::chrono::steady_clock clock;
//利用类的创建调用构造函数初始化一个是时间点
StopWatch() : start(clock::now()) {}
//获取开机到现在执行多少秒
void startUptimeSec() {
std::cout<<"开机多久="<<std::chrono::duration_cast<std::chrono::seconds>(start.time_since_epoch()).count()<<"秒"<<std::endl;
}
long elapsedMs() {
return std::chrono::duration_cast<std::chrono::milliseconds>(
clock::now() - start).count();
}
~StopWatch() {
std::cout<<"运行时间="<<std::chrono::duration_cast<std::chrono::seconds>(clock::now() - start).count()<<"秒"<<std::endl;
}
private:
clock::time_point start;
};
//巧妙的运用类的构造.与析构打印出开与结束时间