计时器

c++中我们经常需要去计算代码的运行时长,或者需要知道代码的运行时长而去加入一些特定条件的使用,此时就需要计时器。一般使用chrono库,可以不需要使用操作系统的库并且几乎支持所有平台,但是如果需要高精度的计时器则需要使用操作系统库。

使用示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <chrono>
#include <thread>

int main()
{
using namespace std::literals::chrono_literals;//后续使用1s时需要

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> time = end - start;//以float方式记录经过时间

std::cout << time.count() << "s" << std::endl;//时间输出
}

一个更具体的使用方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <chrono>
#include <thread>

struct Timer//自助打印运行时间
{
std::chrono::time_point<std::chrono::steady_clock> start, end;
std::chrono::duration<float> time;
Timer()
{
start = std::chrono::high_resolution_clock::now();
}
~Timer()
{
end = std::chrono::high_resolution_clock::now();
time = end - start;

float ms = time.count() * 1000.0f;
float s = time.count();

std::cout << s << "s or" << ms << "ms" << std::endl;
}
};

int main()
{
{//限定作用域
Timer time;
int k = 0;
for (int i = 0; i < 100; i++)
k++;
}
std::cin.get();
}

注意:在上述代码在调试模式(debug)使用时会正常显示每一步的过程,但是如果在发布模式(relase)使用时由于编译器会自动帮我们省略简单计算以达到优化目的,此处代码实际会被简化为哦k被直接赋值100,所以测试显示的时间将会非常短与原方式不和。


资料参考:

youtube上the cherno的cpp系列