Add start/pause to Timer

This commit is contained in:
Jacob Dufault 2017-10-20 13:56:26 -07:00
parent 76cc110cc2
commit f0e9434163
2 changed files with 41 additions and 16 deletions

View File

@ -10,33 +10,47 @@ Timer::Timer() {
long long Timer::ElapsedMicroseconds() const {
std::chrono::time_point<Clock> end = Clock::now();
return std::chrono::duration_cast<std::chrono::microseconds>(end - start)
.count();
long long elapsed = elapsed_;
if (start_.has_value()) {
// TODO: clang-format this file.
elapsed += std::chrono::duration_cast<std::chrono::microseconds>(end - *start_).count();
}
return elapsed;
}
long long Timer::ElapsedMicrosecondsAndReset() {
std::chrono::time_point<Clock> end = Clock::now();
long long microseconds =
std::chrono::duration_cast<std::chrono::microseconds>(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<Clock> end = Clock::now();
long long elapsed =
std::chrono::duration_cast<std::chrono::microseconds>(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();
}
void Timer::Pause() {
assert(start_.has_value());
std::chrono::time_point<Clock> end = Clock::now();
long long elapsed =
std::chrono::duration_cast<std::chrono::microseconds>(end - *start_)
.count();
elapsed_ += elapsed;
start_ = nullopt;
}
void Timer::Resume() {
assert(!start_.has_value());
start_ = Clock::now();
}

View File

@ -1,8 +1,13 @@
#pragma once
#include <optional.h>
#include <chrono>
#include <string>
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 "<foo> 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<Clock> start;
optional<std::chrono::time_point<Clock>> start_;
// Elapsed time.
long long elapsed_ = 0;
};