Skip to content

Instantly share code, notes, and snippets.

@SC-One
Last active January 17, 2025 06:13
Show Gist options
  • Save SC-One/e64d561f5b7086d9221a59bd4b920a37 to your computer and use it in GitHub Desktop.
Save SC-One/e64d561f5b7086d9221a59bd4b920a37 to your computer and use it in GitHub Desktop.
time measurement c++ (profiling out)
#ifndef TIMER_PROFILER_HPP
#define TIMER_PROFILER_HPP
#include <chrono>
#include <string>
namespace TimeProfilerHelper {
template <typename T>
struct ChronoName{
static_assert(std::is_same_v<T, void>, "Unsupported chrono type!");
};
template <>
struct ChronoName<std::chrono::microseconds> {
static constexpr auto value = "microseconds";
};
template <>
struct ChronoName<std::chrono::milliseconds> {
static constexpr auto value = "milliseconds";
};
template <>
struct ChronoName<std::chrono::seconds> {
static constexpr auto value = "seconds";
};
template <>
struct ChronoName<std::chrono::minutes> {
static constexpr auto value = "minutes";
};
template <>
struct ChronoName<std::chrono::hours> {
static constexpr auto value = "hours";
};
template <typename T>
constexpr auto getChronoName() {
return ChronoName<T>::value;
}
} // namespace TimeProfilerHelper
template <class DT = std::chrono::microseconds,
class ClockT = std::chrono::steady_clock>
class TimeProfiler {
public:
TimeProfiler(std::string const& name) : _name(name) { tick(); }
~TimeProfiler() {
tock();
printf("runtime[%s]: %ld %s \n", _name.c_str(), duration().count(), TimeProfilerHelper::getChronoName<DT>());
}
private:
void tick() {
_end = timep_t{};
_start = ClockT::now();
}
void tock() { _end = ClockT::now(); }
template <class T = DT>
auto duration() const {
return std::chrono::duration_cast<T>(_end - _start);
}
private:
using timep_t = typename ClockT::time_point;
timep_t _start = ClockT::now(), _end = {};
std::string const _name;
};
#endif // TIMER_PROFILER_HPP
@SC-One
Copy link
Author

SC-One commented Jan 17, 2025

// use:
TimeProfiler timer("myTimerName");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment