Skip to content

Instantly share code, notes, and snippets.

@pagdot

pagdot/TimeUttils.h

Created Dec 27, 2020
Embed
What would you like to do?
C++ TimeUtils
#ifndef TIMEUTILS_H
#define TIMEUTILS_H
#include <chrono>
#include <iostream>
#include <type_traits>
#include <string>
namespace TimeUtils
{
template <typename TClock = std::chrono::steady_clock>
class Timer
{
public:
Timer() { Reset(); }
void Reset()
{
start = TClock::now();
}
template <typename Unit>
typename Unit::rep Get() const
{
return std::chrono::duration_cast<Unit>(TClock::now() - start).count();
}
std::chrono::milliseconds::rep GetMs() { return Get<std::chrono::milliseconds>(); }
std::chrono::microseconds::rep GetUs() { return Get<std::chrono::microseconds>(); }
std::chrono::seconds::rep GetSec() { return Get<std::chrono::seconds>(); }
std::chrono::minutes::rep GetMin() { return Get<std::chrono::minutes>(); }
std::chrono::hours::rep GetHour() { return Get<std::chrono::hours>(); }
private:
typename TClock::time_point start;
};
template <typename Unit = std::chrono::milliseconds, typename Clock = std::chrono::steady_clock>
class ExecutionTimer
{
public:
ExecutionTimer(std::ostream &out = std::cout) : out(out) {}
void Section(const std::string &name = std::string())
{
if (!section.empty())
printLeave();
section = name;
timer.Reset();
if (!section.empty())
printEnter();
}
~ExecutionTimer() { Section(); }
private:
static std::string getUnit()
{
if constexpr (std::is_base_of_v<std::chrono::milliseconds, Unit>)
{
return "ms";
}
else if constexpr (std::is_base_of_v<std::chrono::microseconds, Unit>)
{
return "us";
}
else if constexpr (std::is_base_of_v<std::chrono::seconds, Unit>)
{
return "sec";
}
else if constexpr (std::is_base_of_v<std::chrono::minutes, Unit>)
{
return "min";
}
else if constexpr (std::is_base_of_v<std::chrono::hours, Unit>)
{
return "h";
}
}
void printEnter() { out << "==> " << section << std::endl; }
void printLeave() { out << "<== " << section << " after " << timer.template Get<std::chrono::milliseconds>() << getUnit() << std::endl; }
std::string section;
Timer<Clock> timer;
std::ostream& out;
};
} // namespace TimeUtils
#endif //TIMEUTILS_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment