本节介绍c++中计时,计时在程序流程控制和性能测试中有着非常重要的作用。
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
using namespace std::literals::chrono_literals;
//获取当前时间
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(1s);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<float> duration = end - start;
//结果不同配置的硬件执行结果不同
std::cout << duration.count() << std::endl;
std::cin.get();
}
更进一步的计时函数,创建一个简单的定时器,使用自己构建的定时器进行计时。
#include <iostream>
#include <chrono>
#include <thread>
class Timer
{
public:
std::chrono::steady_clock::time_point start, end;
std::chrono::duration<float> duration;
Timer()
{
start = std::chrono::high_resolution_clock::now();
}
~Timer()
{
end = std::chrono::high_resolution_clock::now();
duration = end - start;
float ms = duration.count() * 1000.0f;
std::cout << "持续时间:" << ms << std::endl;
}
};
void Function()
{
Timer t;
//计算打印10000次"Hello World!"需要的时间
for (int i = 0; i < 100; i++)
{
std::cout << "Hello World!\n";
}
}
int main()
{
using namespace std::literals::chrono_literals;
Function();
std::cin.get();
}