Skip to content

Instantly share code, notes, and snippets.

@nickdowell
Last active September 6, 2023 21:12
Show Gist options
  • Save nickdowell/de64edbcdb0b466229e902861ff5eb65 to your computer and use it in GitHub Desktop.
Save nickdowell/de64edbcdb0b466229e902861ff5eb65 to your computer and use it in GitHub Desktop.
#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