Skip to main content

C++ 测量时间间隔

· 2 min read
therainisme

样例

#include <chrono>

void example() {
std::chrono::duration<double, std::milli> total_time(0);

auto start = std::chrono::steady_clock::now();
// do something
auto end = std::chrono::steady_clock::now();

total_time += end - start;

std::cout << "total time: " << total_time.count() << "ms" << std::endl;
}

补充说明

std::chrono::high_resolution_clock

std::chrono::high_resolution_clock 通常是 std::chrono::steady_clockstd::chrono::system_clock 的别名。不推荐直接使用 high_resolution_clock,而是应该根据需求使用 steady_clocksystem_clock

std::chrono::steady_clock

cppreference

Class std::chrono::steady_clock represents a monotonic clock. The time points of this clock cannot decrease as physical time moves forward and the time between ticks of this clock is constant. This clock is not related to wall clock time (for example, it can be time since last reboot), and is most suitable for measuring intervals.

它是测量时间间隔的最佳选择,不受系统时间的影响。

std::chrono::system_clock

它的好处是可以映射系统时间,不过,它可能不是单调的。如果先获取时间,再调整系统时间,得到的时间间隔是将是负数