diff --git a/src/timer.h b/src/timer.h new file mode 100644 index 0000000000000000000000000000000000000000..e73ebc4453675f8d8e523baad66bc03700472819 --- /dev/null +++ b/src/timer.h @@ -0,0 +1,98 @@ +#ifndef WOLF_TIMER_H_ +#define WOLF_TIMER_H_ + +#include <chrono> + +namespace wolf +{ +namespace details +{ +using std::chrono::hours; +using std::chrono::minutes; +using std::chrono::seconds; +using std::chrono::milliseconds; +using std::chrono::microseconds; +using std::chrono::nanoseconds; + +template<typename _Clock, typename _Dur> +using time_point = std::chrono::time_point<_Clock, _Dur>; + +using wolf_time_unit = nanoseconds; +using wolf_clock_t = std::chrono::_V2::high_resolution_clock; +} // namespace details + +/** + * @brief Timer. A tic-toc timer. + * + * Mesure the elapsed time between construction - or tic() - + * and toc(). The elapsed time is expressed in unit. + * + * @param unit. The time unit. + * @see unit + */ +template <typename unit> +class Timer +{ +public: + + /** + * @brief Timer. Launch the timer. + */ + Timer(): start_(now()) { } + + /** + * @brief ~Timer. Default desctructor. + */ + ~Timer() = default; + + /** + * @brief tic. Reset the timer. + */ + void tic() + { + start_ = now(); + } + + /** + * @brief toc. Return this elapsed time since construction or last tic(). + * @return double. The elapsed time. + * @see tic() + */ + template <typename T = int64_t> + T toc() + { + return static_cast<T>(cast_d(now() - start_).count()); + } + +protected: + + details::time_point<details::wolf_clock_t, unit> start_; + + template <typename... Args> + auto cast_d(Args&&... args) -> + decltype(std::chrono::duration_cast<unit>(std::forward<Args>(args)...)) + { + return std::chrono::duration_cast<unit>(std::forward<Args>(args)...); + } + + template <typename... Args> + auto cast(Args&&... args) -> + decltype(std::chrono::time_point_cast<unit>(std::forward<Args>(args)...)) + { + return std::chrono::time_point_cast<unit>(std::forward<Args>(args)...); + } + + auto now() -> + decltype(std::declval<Timer<unit>>().cast(details::wolf_clock_t::now())) + { + return cast(std::chrono::system_clock::now()); + } +}; + +using timer_secs = Timer<details::seconds>; +using timer_msecs = Timer<details::milliseconds>; +using timer_usecs = Timer<details::microseconds>; +using timer_nsecs = Timer<details::microseconds>; + +} // namespace wolf +#endif // WOLF_TIMER_H_