Browse Source

Util: Add timer class

master
Riyyi 3 years ago
parent
commit
86aeae3c8e
  1. 72
      src/util/timer.cpp
  2. 43
      src/util/timer.h

72
src/util/timer.cpp

@ -0,0 +1,72 @@
#include <algorithm> // max, min
#include <chrono> // high_resolution_clock seconds, milliseconds, microseconds, nanoseconds
#include <cstdint> // uint64_t
#include "util/timer.h"
namespace Util {
Timer::Timer()
{
m_start = std::chrono::high_resolution_clock::now();
}
Timer Timer::operator-(const Timer& timer)
{
return Timer(TimePoint { m_start - timer.start() });
}
template<typename To, typename From>
To Timer::to(From from)
{
return std::chrono::duration_cast<To>(from);
}
uint64_t Timer::toSeconds()
{
return to<std::chrono::seconds>(m_start.time_since_epoch()).count();
}
uint64_t Timer::toMilliseconds()
{
return to<std::chrono::milliseconds>(m_start.time_since_epoch()).count();
}
uint64_t Timer::toMicroseconds()
{
return to<std::chrono::microseconds>(m_start.time_since_epoch()).count();
}
uint64_t Timer::toNaneseconds()
{
return to<std::chrono::nanoseconds>(m_start.time_since_epoch()).count();
}
template<typename T>
uint64_t Timer::elapsed()
{
auto now = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<T>(now - m_start).count();
}
uint64_t Timer::elapsedSeconds()
{
return elapsed<std::chrono::seconds>();
}
uint64_t Timer::elapsedMilliseconds()
{
return elapsed<std::chrono::milliseconds>();
}
uint64_t Timer::elapsedMicroseconds()
{
return elapsed<std::chrono::microseconds>();
}
uint64_t Timer::elapsedNanoseconds()
{
return elapsed<std::chrono::nanoseconds>();
}
} // namespace Util

43
src/util/timer.h

@ -0,0 +1,43 @@
#ifndef TIMER_H
#define TIMER_H
#include <chrono> // high_resolution_clock
#include <cstdint> // uint64_t
namespace Util {
using TimePoint = std::chrono::high_resolution_clock::time_point;
class Timer {
public:
Timer();
Timer(const TimePoint& timePoint)
: m_start(timePoint)
{
}
Timer operator-(const Timer& timer);
template<typename To, typename From>
To to(From from);
uint64_t toSeconds();
uint64_t toMilliseconds();
uint64_t toMicroseconds();
uint64_t toNaneseconds();
template<typename T>
uint64_t elapsed();
uint64_t elapsedSeconds();
uint64_t elapsedMilliseconds();
uint64_t elapsedMicroseconds();
uint64_t elapsedNanoseconds();
const TimePoint& start() const { return m_start; }
private:
TimePoint m_start;
};
} // namespace Util
#endif // TIMER_H
Loading…
Cancel
Save