diff --git a/src/telemetry/Manager.cc b/src/telemetry/Manager.cc index f8cd56d8f2..5bee940a25 100644 --- a/src/telemetry/Manager.cc +++ b/src/telemetry/Manager.cc @@ -4,9 +4,12 @@ #include "caf/telemetry/metric_registry.hpp" +#include + #include "zeek/3rdparty/doctest.h" #include "zeek/telemetry/Detail.h" +#include "zeek/telemetry/Timer.h" namespace zeek::telemetry { @@ -524,6 +527,16 @@ SCENARIO("telemetry managers provide access to histogram families") auto second = family.GetOrAdd({{"protocol", "udp"}}); CHECK_NE(first, second); } + AND_THEN("Timers add observations to histograms") + { + auto hg = family.GetOrAdd({{"protocol", "tst"}}); + CHECK_EQ(hg.Sum(), 0.0); + { + Timer observer{hg}; + std::this_thread::sleep_for(1ms); + } + CHECK_NE(hg.Sum(), 0.0); + } } } } diff --git a/src/telemetry/Timer.h b/src/telemetry/Timer.h new file mode 100644 index 0000000000..ad02a4c09c --- /dev/null +++ b/src/telemetry/Timer.h @@ -0,0 +1,55 @@ +// See the file "COPYING" in the main distribution directory for copyright. + +#pragma once + +#include + +namespace zeek::telemetry { + +/// Convenience helper for measuring durations such as latency using a histogram +/// with second resolution. The measurement starts when creating the objects and +/// finishes when the Timer goes out of scope. +class Timer { +public: + using Clock = std::chrono::steady_clock; + + [[nodiscard]] explicit Timer(DblHistogram h) : h_(h) + { + start_ = Clock::now(); + } + + Timer(const Timer&) = delete; + + Timer&operator=(const Timer&) = delete; + + ~Timer() + { + Observe(h_, start_); + } + + /// @return The histogram handle. + auto Handle() const noexcept + { + return h_; + } + + /// @return The recorded start time. + auto Started() const noexcept + { + return start_; + } + + /// Calls `h.Observe` with the time passed since `start`. + static void Observe(DblHistogram h, Clock::time_point start) + { + using DblSec = std::chrono::duration; + if ( auto end = Clock::now(); end > start ) + h.Observe(std::chrono::duration_cast(end - start).count()); + } + +private: + DblHistogram h_; + Clock::time_point start_; +}; + +} // namespace zeek::telemetry