Last active
September 6, 2023 21:12
-
-
Save nickdowell/de64edbcdb0b466229e902861ff5eb65 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
#include <unordered_map> | |
class avg_timer | |
{ | |
public: | |
avg_timer(const char *name, int batch = 120) : name_(name), batch_(batch) {} | |
avg_timer(const scope_timer &) = delete; | |
~avg_timer() noexcept | |
{ | |
auto elapsed = std::chrono::steady_clock::now() - start_; | |
auto &it = stats_[name_]; | |
it.microseconds += std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); | |
if (++it.iterations >= batch_) | |
{ | |
auto us = it.microseconds / it.iterations; | |
if (us >= 1000000) | |
printf("avg_timer(%s) = %g s\n", name_, (us / 1000) / 1000.0); | |
else | |
printf("avg_timer(%s) = %g ms\n", name_, us / 1000.0); | |
it.iterations = 0; | |
it.microseconds = 0; | |
} | |
} | |
private: | |
struct stats | |
{ | |
int iterations {0}; | |
std::chrono::microseconds::rep microseconds {0}; | |
}; | |
const char *name_; | |
int batch_; | |
std::chrono::steady_clock::time_point start_ {std::chrono::steady_clock::now()}; | |
static std::unordered_map<std::string, stats> stats_; | |
}; | |
std::unordered_map<std::string, avg_timer::stats> avg_timer::stats_; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment