文章

05.C++时间

05.C++时间

C++ 的计时

计时的使用很重要。在逐渐开始集成更多复杂的特性时,如果编写性能良好的代码时,需要用到计时来看到差异。

利用 chrono 类计时

  • 包含头文件 #include
  • 获取当前时间
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
std::chrono::time_point<std::chrono::steady_clock> start = std::chrono::high_resolution_clock::now();
//或者,使用auto关键字
auto  start = std::chrono::high_resolution_clock::now();
auto  end = std::chrono::high_resolution_clock::now();
// ----------------------------------------------------------
//实例
#include <iostream>
#include <chrono>
#include <thread>

int main() {
    //literals:文字
    using namespace std::literals::chrono_literals; //有了这个,才能用下面1s中的's'
    auto start = std::chrono::high_resolution_clock::now(); //记录当前时间
    std::this_thread::sleep_for(1s);    //休眠1s,实际会比1s大。函数本身有开销。
    auto end = std::chrono::high_resolution_clock::now();   //记录当前时间
    std::chrono::duration<float> duration = end - start;    //也可以写成 auto duration = end - start; 
    std::cout << duration.count() << "s" << std::endl;
    return 0;
}
  • 获得时间差:
1
2
3
std::chrono::duration<float> duration = end - start;
//或者
auto duration = end - start;

注意:在自定义计时器类的构造函数、析构函数中,不要使用 auto 关键字,应该在计时器类的构造函数、析构函数定义 start、end、duration 变量。

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
struct Timer   //写一个计时器类。
{
    std::chrono::time_point<std::chrono::steady_clock> start, end;
    std::chrono::duration<float> duration;

    Timer()
    {
        start = std::chrono::steady_clock::now(); //如果使用auto关键字会出现警告
    }

    ~Timer()
    {
        end = std::chrono::steady_clock::now();
        duration = end - start;

        float ms = duration.count() * 1000;
        std::cout << "Timer took " << ms << " ms" << std::endl;
    }
};
void Function()
{
    Timer timer;
    for (int i = 0; i < 100; i++)
        std::cout << "Hello\n"; //相比于std::endl更快
}

int main()
{
    Function();
}
本文由作者按照 CC BY 4.0 进行授权