diff options
author | Robin Voetter <robin@voetter.nl> | 2023-06-15 22:23:47 (GMT) |
---|---|---|
committer | Robin Voetter <robin@voetter.nl> | 2023-06-15 22:23:47 (GMT) |
commit | dd8f62c9088f94a4081f84cac0d05beb695f88f7 (patch) | |
tree | 94b6733445d96ab98b5329d9222aa4f067a06a88 | |
parent | 36843d387cb0621c1a288179af223d4f1410be73 (diff) | |
download | Ninja-dd8f62c9088f94a4081f84cac0d05beb695f88f7.zip Ninja-dd8f62c9088f94a4081f84cac0d05beb695f88f7.tar.gz Ninja-dd8f62c9088f94a4081f84cac0d05beb695f88f7.tar.bz2 |
metrics: use chrono to convert ticks to micros
This was previously causing undefined behavior, as multiplying dt by 1000000
overflowed on some systems. Fixes #2301.
-rw-r--r-- | src/metrics.cc | 9 |
1 files changed, 7 insertions, 2 deletions
diff --git a/src/metrics.cc b/src/metrics.cc index 9a4dd12..632ae43 100644 --- a/src/metrics.cc +++ b/src/metrics.cc @@ -48,12 +48,17 @@ constexpr int64_t GetFrequency() { int64_t TimerToMicros(int64_t dt) { // dt is in ticks. We want microseconds. - return (dt * 1000000) / GetFrequency(); + return chrono::duration_cast<chrono::microseconds>( + std::chrono::steady_clock::duration{ dt }) + .count(); } int64_t TimerToMicros(double dt) { // dt is in ticks. We want microseconds. - return (dt * 1000000) / GetFrequency(); + using DoubleSteadyClock = + std::chrono::duration<double, std::chrono::steady_clock::period>; + return chrono::duration_cast<chrono::microseconds>(DoubleSteadyClock{ dt }) + .count(); } } // anonymous namespace |