#include <iostream>
#include <chrono>
class Timer
{
public:
Timer(){
m_StartTimePoint = std::chrono::high_resolution_clock::now();
}
~Timer(){
stop();
}
void stop()
{
auto endTimePoint = std::chrono::high_resolution_clock::now();
auto start = std::chrono::time_point_cast<std::chrono::microseconds>(m_StartTimePoint).time_since_epoch().count();
auto end = std::chrono::time_point_cast<std::chrono::microseconds>(endTimePoint).time_since_epoch().count();
auto duration = end-start;
double ms = duration*0.001;
std::cout<<"运行花费:"<<duration<<"微秒,"<<ms<<"毫秒"<<std::endl;
}
private:
std::chrono::time_point<std::chrono::high_resolution_clock> m_StartTimePoint;
};
int main()
{
long number =0;
{
Timer timer;
for (int i=0;i<10000000;i++) {
number+=1;
}
}
std::cout << number << std::endl;
return 0;
}
C++计时器
该代码示例展示了一个简单的C++类Timer,利用chrono库来测量代码段的执行时间。类在构造时开始计时,析构函数中停止计时并打印出以微秒和毫秒为单位的运行时间。在main函数中,对一个循环进行了计时以展示Timer类的用法。
摘要由CSDN通过智能技术生成