一 简介
- C++11 在chrono库中提供了三种时钟 clock: system_clock,steady_clock 和 high_resolution_clock。
- 头文件 < chrono >。
二 system_clock
-
system_clock 来自系统范围实时时钟的壁钟时间(wall clock)。
-
system_clock是唯一有能力映射其时间点到 C 风格时间的 C++ 时钟。
It is the only C++ clock that has the ability to map its time points to C-style time.
-
system_clock可以不单调:大多数系统上,系统时间可以在任何时候被调节。
It may not be monotonic: on most systems, the system time can be adjusted at any moment.
The system_clock’s time value can be internally adjusted at any time by the operating system. -
例子
// 是否为稳定时钟 cout << "system_clock::is_steady: " << std::boolalpha << system_clock::is_steady << endl; { auto start = system_clock::now(); int i = 0; while (i < 10000) i++; duration<double> time = system_clock::now() - start; cout << "time: " << time.count() << endl; } { auto t = system_clock::to_time_t(system_clock::now()); // to_time_t cout << asctime(gmtime(&t)) << endl; cout << asctime(localtime(&t)) << endl; duration<double> time = system_clock::now() - system_clock::from_time_t(t); // from_time_t cout << "time: " << time.count() << endl; }
-
输出
system_clock::is_steady: false time: 1.61e-05 Tue Sep 29 03:55:00 2020 Tue Sep 29 11:55:00 2020 time: 0.506771
三 steady_clock
-
steady_clock是单调时钟。
Class std::chrono::steady_clock represents a monotonic clock.
-
常用于耗时计算 。(stopwatch)
-
例子
cout << "steady_clock::is_steady: " << std::boolalpha << steady_clock::is_steady << endl; { auto start = steady_clock::now(); int i = 0; while (i < 10000) i++; duration<double> time = steady_clock::now() - start; cout << "time: " << time.count() << endl; }
-
输出
steady_clock::is_steady: true time: 1.6078e-05
四 high_resolution_clock
-
high_resolution_clock是当前系统能够提供的最高精度的时钟。
-
high_resolution_clock在不同标准库实现之间实现不一致,应该避免使用它。通常它只是 std::chrono::steady_clock 或 std::chrono::system_clock 的别名,但实际是哪个取决于库或配置。
It may be an alias of std::chrono::system_clock or std::chrono::steady_clock, or a third, independent clock.
-
例子
cout << "high_resolution_clock::is_steady: " << std::boolalpha << high_resolution_clock::is_steady << endl; { auto start = high_resolution_clock::now(); int i = 0; while (i < 10000) i++; duration<double> time = high_resolution_clock::now() - start; cout << "time: " << time.count() << endl; }
-
输出
high_resolution_clock::is_steady: true time: 1.6077e-05