Created
June 21, 2022 14:35
-
-
Save byBretema/ef33f3a9ffacf1850f405460deb573c0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <chrono> | |
#include <functional> | |
#include <string> | |
#include <iostream> | |
#include <cstdint> | |
class DCTimer | |
{ | |
using Clock = std::chrono::high_resolution_clock; | |
using TimeUnit = std::chrono::milliseconds; | |
public: | |
DCTimer(QString const & msg = "", | |
bool showOnDestroy = false, | |
std::function<bool(int32_t)> const & fn = nullptr) | |
: m_msg(msg) | |
, m_showOnDestroy(showOnDestroy) | |
, m_fn(fn) {} | |
DCTimer(QString const & msg = "", | |
std::function<bool(int32_t)> const & fn = nullptr) | |
: DCTimer(msg, true, fn) {} | |
~DCTimer() | |
{ | |
if (m_showOnDestroy && runUserFn()) | |
showElapsed(); | |
} | |
inline void reset(QString const & msg = "") | |
{ | |
m_msg = msg!="" ? msg : ( m_msg + "_" + (m_resetCount++) ); | |
m_begin = Clock::now(); | |
} | |
inline void showAndReset(QString const & msg = "") | |
{ | |
if (runUserFn()) | |
showElapsed(); | |
reset(msg); | |
} | |
inline int32_t getTime() const | |
{ | |
return std::chrono::duration_cast<TimeUnit>( Clock::now() - m_begin ).count(); | |
} | |
inline void showElapsed() const | |
{ | |
std::cout << "[DCTimer] => (" << getTime() << " ms) : " << m_msg; | |
} | |
private: | |
inline bool runUserFn() | |
{ | |
return m_fn ? m_fn(getTime()) : true; | |
} | |
Clock::time_point m_begin = Clock::now(); | |
QString m_msg = ""; | |
bool m_showOnDestroy = true; | |
std::function<bool(int32_t)> m_fn = nullptr; | |
int32_t m_resetCount = 1; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment