geode/loader/include/Geode/utils/timer.hpp

86 lines
2.6 KiB
C++
Raw Normal View History

2022-07-30 12:24:03 -04:00
#pragma once
#include <chrono>
namespace geode::utils {
template <typename T>
struct is_chrono_duration {
static constexpr bool value = false;
};
template <typename Rep, typename Period>
struct is_chrono_duration<std::chrono::duration<Rep, Period>> {
static constexpr bool value = true;
};
2022-10-30 14:59:20 -04:00
template <class Clock = std::chrono::high_resolution_clock>
2022-07-30 12:24:03 -04:00
class Timer {
public:
using clock_point = std::chrono::time_point<Clock>;
private:
clock_point m_start;
public:
Timer() {
m_start = Clock::now();
}
void reset() {
m_start = Clock::now();
}
2022-10-30 14:59:20 -04:00
clock_point time() const {
return m_start;
}
2022-07-30 12:24:03 -04:00
2022-10-30 14:59:20 -04:00
template <typename Duration = std::chrono::milliseconds>
2022-07-30 12:24:03 -04:00
int64_t elapsed() const {
2022-10-30 14:59:20 -04:00
static_assert(
is_chrono_duration<Duration>::value, "Duration must be a std::chrono::duration"
);
2022-07-30 12:24:03 -04:00
auto end = Clock::now();
return std::chrono::duration_cast<Duration>(end - m_start).count();
}
2022-10-30 14:59:20 -04:00
template <typename Duration = std::chrono::milliseconds>
2022-07-30 12:24:03 -04:00
std::string elapsedAsString() const {
2022-10-30 14:59:20 -04:00
static_assert(
is_chrono_duration<Duration>::value, "Duration must be a std::chrono::duration"
);
2022-07-30 12:24:03 -04:00
if constexpr (std::is_same<Duration, std::chrono::milliseconds>::value) {
return std::to_string(this->elapsed<Duration>()) + "ms";
}
else if constexpr (std::is_same<Duration, std::chrono::microseconds>::value) {
return std::to_string(this->elapsed<Duration>()) + "us";
}
else if constexpr (std::is_same<Duration, std::chrono::nanoseconds>::value) {
return std::to_string(this->elapsed<Duration>()) + "ns";
}
else {
// static_assert(!std::is_same_v<bool, bool>, "Unsupported duration type");
}
}
};
2022-10-30 14:59:20 -04:00
template <
2022-07-30 12:24:03 -04:00
typename Duration = std::chrono::milliseconds,
2022-10-30 14:59:20 -04:00
class Clock = std::chrono::high_resolution_clock>
2022-07-30 12:24:03 -04:00
struct LogPerformance {
std::ostream& m_output;
std::string m_msg;
Timer<Clock> m_timer;
// @geode-ignore(geode-alternative)
2022-10-30 14:59:20 -04:00
LogPerformance(std::string const& msg = "", std::ostream& out = std::cout) :
m_msg(msg), m_output(out) {
2022-07-30 12:24:03 -04:00
m_timer = Timer<Clock>();
};
2022-10-30 14:59:20 -04:00
2022-07-30 12:24:03 -04:00
~LogPerformance() {
2022-10-30 14:59:20 -04:00
m_output << "Running \"" << m_msg << "\" took "
<< m_timer.template elapsedAsString<Duration>() << std::endl;
2022-07-30 12:24:03 -04:00
}
};
}