From 07455d0b3074243ff9cc86f42babf652f6b96337 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20B=C3=A9raud?= Date: Wed, 2 Jul 2025 01:08:47 -0400 Subject: [PATCH] debug_utils: add StatsTimer Change-Id: I6ad09f94ba4fd01e189b11d55bb1b2861f5a6c39 --- src/debug_utils.h | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/src/debug_utils.h b/src/debug_utils.h index ae8a4cdf4..6376fa5b9 100644 --- a/src/debug_utils.h +++ b/src/debug_utils.h @@ -62,7 +62,7 @@ public: } void print(std::string_view action) const { - JAMI_DBG() << name_ << ": " << action << " after " << dht::print_duration(Clock::now() - start_); + JAMI_LOG("{}: {} after {}", name_, action, dht::print_duration(Clock::now() - start_)); } private: @@ -70,6 +70,48 @@ private: std::chrono::time_point start_; }; +/* + * Ex: + * STATS_TIMER(TaskName); + * std::this_thread::sleep_for(std::chrono::milliseconds(10)); + * // Timer automatically prints stats on destruction + */ +template +class StatsTimer +{ + using time_point = std::chrono::time_point; + using duration = Clock::duration; +public: + StatsTimer() : start_(Clock::now()) {} + + ~StatsTimer() { + auto duration = Clock::now() - start_; + auto [avg, count] = inc(duration); + JAMI_LOG("{}: end after {}", Tag::name(), dht::print_duration(duration)); + if (count > 1) { + JAMI_LOG("{}: Average duration: {} ({})", Tag::name(), dht::print_duration(avg), count); + } + } +private: + time_point start_; + static inline std::mutex mutex_; + static inline duration total_duration_ {}; + static inline duration::rep count_ {0}; + + std::pair inc(duration dt) { + std::lock_guard lock(mutex_); + total_duration_ += dt; + count_++; + return {total_duration_ / count_, count_}; + } +}; + +#define STATS_TIMER(tag) \ + struct StatsTimerTag_##tag { \ + static constexpr std::string_view name() { return #tag; } \ + }; \ + jami::debug::StatsTimer stats_timer_##tag + /** * Audio logger. Writes a wav file from raw PCM or AVFrame. Helps debug what goes wrong with audio. */