C++学习笔记 30 计时器
一、计时器 (OS vs C++)
在C++11之后,我们有chrono,它是C++库的一部分,不需要去使用操作系统库;但在有chrono之前,如果你想要高分辨率的时间,非常精确的计时器,那你需要使用操作系统库。在Windows操作系统中,有一个叫QueryPerformanceCounter的东西,现在仍然可以使用那些东西,事实上,如果你想要更多地控制计时,控制CPU的计时能力,那么你可能会使用平台特定的库。
二、作用
计算函数以及特定代码允许需要的时间
#include<iostream>
#include<chrono>
#include<thread>
struct Timer {
std::chrono::steady_clock::time_point start, end;
std::chrono::duration<float> duration;
public:
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 << "Timer took " << ms << " ms." << std::endl;
}
};
void TimerStructFunction() {
Timer timer;
for (int i = 0; i < 100; i++) {
std::cout << "Hello " << i << std::endl;
std::cout << "Hello " << i << "\n"; //\n会执行更快
}
}
void TestTimer() {
auto start = std::chrono::high_resolution_clock::now();
using namespace std::literals::chrono_literals;
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() << "s" << std::endl;
}
int main() {
TestTimer();
TimerStructFunction();
}

浙公网安备 33010602011771号