1.毫秒级:
写一个头文件:
#include <iostream>
#include <chrono>
using namespace std;
class Timer
{
public:
Timer(): t1(res::zero()),t2(res::zero())
{
setTime();
}
~Timer()
{}
void setTime()
{
t1 = clock::now();
}
void getTime()
{
t2 = clock::now();
cout << "运行时间为: "
<< chrono::duration_cast<res>(t2 - t1).count() / 1e3 << "ms." << endl;
}
private:
typedef chrono::high_resolution_clock clock;
typedef chrono::microseconds res;
clock::time_point t1;
clock::time_point t2;
};
保存,在要用上这个头文件的项目里添加头文件路径:(VS2019)
项目- 属性- C/C++ -常规-附加包含目录 -将头文件路径输入进去。
Timer timer; //调用自己写的Timer类计算时间
/*
此处为所要测的函数
*/
timer.getTime();
2.秒级:
头文件:#include<ctime>
clock_t startTime, endTime;
startTime = clock();
/*
此处为所要测的函数
*/
endTime = clock();
cout << "运行时间为:" << ((double)(endTime)-(double)startTime) / CLOCKS_PER_SEC << "s" << endl;