Browse Source

Util: Add pause() and resume() to Timer

master
Riyyi 2 years ago
parent
commit
11fdc64447
  1. 51
      src/util/timer.cpp
  2. 11
      src/util/timer.h

51
src/util/timer.cpp

@ -1,21 +1,57 @@
#include <chrono> // high_resolution_clock, seconds, milliseconds, microseconds, nanoseconds #include <chrono> // high_resolution_clock, seconds, milliseconds, microseconds, nanoseconds
#include <cstdint> // uint64_t #include <cstdint> // uint64_t
#include <cstdio> // printf #include <cstdio> // printf
#include "util/timer.h" #include "util/timer.h"
namespace Util { namespace Util {
Timer::Timer() Timer::Timer()
: m_start(std::chrono::high_resolution_clock::now()) : m_running(true)
, m_accumulated(TimePoint::min())
, m_start(now())
{ {
} }
Timer::Timer(const TimePoint& timePoint)
: m_running(true)
, m_accumulated(TimePoint::min())
, m_start(timePoint)
{
}
// -----------------------------------------
Timer Timer::operator-(const Timer& timer) Timer Timer::operator-(const Timer& timer)
{ {
return Timer(TimePoint { m_start - timer.start() }); return Timer(TimePoint { m_start - timer.start() });
} }
TimePoint Timer::now()
{
return std::chrono::high_resolution_clock::now();
}
void Timer::pause()
{
if (!m_running) {
return;
}
m_accumulated += now() - m_start;
m_running = false;
}
void Timer::resume()
{
if (m_running) {
return;
}
m_running = true;
m_start = now();
}
template<typename To, typename From> template<typename To, typename From>
To Timer::to(From from) To Timer::to(From from)
{ {
@ -45,8 +81,15 @@ uint64_t Timer::toNanoseconds()
template<typename T> template<typename T>
uint64_t Timer::elapsed() uint64_t Timer::elapsed()
{ {
auto now = std::chrono::high_resolution_clock::now(); uint64_t elapsed = 0;
return std::chrono::duration_cast<T>(now - m_start).count();
if (m_running) {
elapsed += std::chrono::duration_cast<T>(now() - m_start).count();
}
elapsed += std::chrono::duration_cast<T>(m_accumulated - TimePoint::min()).count();
return elapsed;
} }
uint64_t Timer::elapsedSeconds() uint64_t Timer::elapsedSeconds()

11
src/util/timer.h

@ -11,13 +11,14 @@ using TimePoint = std::chrono::high_resolution_clock::time_point;
class Timer { class Timer {
public: public:
Timer(); Timer();
Timer(const TimePoint& timePoint) Timer(const TimePoint& timePoint);
: m_start(timePoint)
{
}
Timer operator-(const Timer& timer); Timer operator-(const Timer& timer);
static TimePoint now();
void pause();
void resume();
template<typename To, typename From> template<typename To, typename From>
To to(From from); To to(From from);
uint64_t toSeconds(); uint64_t toSeconds();
@ -37,6 +38,8 @@ public:
const TimePoint& start() const { return m_start; } const TimePoint& start() const { return m_start; }
private: private:
bool m_running { true };
TimePoint m_accumulated;
TimePoint m_start; TimePoint m_start;
}; };

Loading…
Cancel
Save