简介
chrono是C++的时间库,源于boost,在C++11中纳入了标准,
相比于过去常用的GetTickCount()计时,chrono具有更高的精度,据说能够到达纳秒级别
示例代码
#include <iostream>
#include <chrono>
#include <iomanip>
using namespace std;
void main()
{
auto start = chrono::high_resolution_clock::now(); //开始时间
double db = 0; //代码运行时间
for (int i = 0; i < 100000; i++)
{
db += i;
}
auto end = chrono::high_resolution_clock::now(); //结束时间
__int64 duration = (end - start).count();
cout << "程序运行时间:" << setprecision(10) << duration / 1000000000.0 << "s"
<< "; " << duration / 1000000.0 << "ms"
<< "; " << duration / 1000.0 << "us"
<< endl;
cin.get();
}
这里也附上基于GetTickCount()的计时方法
#include<iostream>
#include<Windows.h>
using namespace std;
int main()
{
DWORD start_time = GetTickCount(); //开始时间; GetTickCount()获取从操作系统启动开始所经过的毫秒数,返回值是DWORD类型
for (int i = 0; i < 100000; i++)
{
i++;
}
DWORD end_time = GetTickCount(); //结束时间;
cout << "运行时间为:" << (end_time - start_time) << "ms" << endl;
system("pause");
return 0;
}
实际测试可以看出两者的计时是存在差距的,
据参考资料GetTickCount_百度百科的解释,GetTickCount()的精度大概只有18ms左右。