diff --git a/src/timer.cc b/src/timer.cc index 1c93b28c..81e0e6b0 100644 --- a/src/timer.cc +++ b/src/timer.cc @@ -10,33 +10,47 @@ Timer::Timer() { long long Timer::ElapsedMicroseconds() const { std::chrono::time_point end = Clock::now(); - return std::chrono::duration_cast(end - start) - .count(); + long long elapsed = elapsed_; + if (start_.has_value()) { + // TODO: clang-format this file. + elapsed += std::chrono::duration_cast(end - *start_).count(); + } + return elapsed; } long long Timer::ElapsedMicrosecondsAndReset() { - std::chrono::time_point end = Clock::now(); - long long microseconds = - std::chrono::duration_cast(end - start) - .count(); + long long elapsed = ElapsedMicroseconds(); Reset(); - return microseconds; + return elapsed; } void Timer::Reset() { - start = Clock::now(); + start_ = Clock::now(); + elapsed_ = 0; } void Timer::ResetAndPrint(const std::string& message) { - std::chrono::time_point end = Clock::now(); - long long elapsed = - std::chrono::duration_cast(end - start) - .count(); - + long long elapsed = ElapsedMicroseconds(); long long milliseconds = elapsed / 1000; long long remaining = elapsed - milliseconds; - LOG_S(INFO) << message << " took " << milliseconds << "." << remaining << "ms"; Reset(); -} \ No newline at end of file +} + +void Timer::Pause() { + assert(start_.has_value()); + + std::chrono::time_point end = Clock::now(); + long long elapsed = + std::chrono::duration_cast(end - *start_) + .count(); + + elapsed_ += elapsed; + start_ = nullopt; +} + +void Timer::Resume() { + assert(!start_.has_value()); + start_ = Clock::now(); +} diff --git a/src/timer.h b/src/timer.h index 15c68e90..8c1856c1 100644 --- a/src/timer.h +++ b/src/timer.h @@ -1,8 +1,13 @@ #pragma once +#include + #include #include +using std::experimental::nullopt; +using std::experimental::optional; + struct Timer { using Clock = std::chrono::high_resolution_clock; @@ -17,7 +22,13 @@ struct Timer { void Reset(); // Resets timer and prints a message like " took 5ms" void ResetAndPrint(const std::string& message); + // Pause the timer. + void Pause(); + // Resume the timer after it has been paused. + void Resume(); // Raw start time. - std::chrono::time_point start; + optional> start_; + // Elapsed time. + long long elapsed_ = 0; };