From f0e943416307857c2e2bd9787c59adfcc532f66a Mon Sep 17 00:00:00 2001 From: Jacob Dufault Date: Fri, 20 Oct 2017 13:56:26 -0700 Subject: [PATCH] Add start/pause to Timer --- src/timer.cc | 44 +++++++++++++++++++++++++++++--------------- src/timer.h | 13 ++++++++++++- 2 files changed, 41 insertions(+), 16 deletions(-) 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; };