File indexing completed on 2025-12-16 09:23:23
0001
0002
0003
0004
0005
0006
0007
0008
0009 #include "Acts/Utilities/ScopedTimer.hpp"
0010
0011 #include <chrono>
0012 #include <cmath>
0013
0014 namespace Acts {
0015
0016 ScopedTimer::ScopedTimer(const std::string& name, const Logger& logger,
0017 Logging::Level lvl)
0018 : m_name(name), m_lvl(lvl), m_logger(&logger) {
0019 m_start = clock_type::now();
0020 }
0021
0022 ScopedTimer::~ScopedTimer() {
0023 auto end = clock_type::now();
0024 auto duration =
0025 std::chrono::duration_cast<std::chrono::microseconds>(end - m_start);
0026 if (m_logger->doPrint(m_lvl)) {
0027 std::ostringstream oss;
0028 oss << m_name << " took " << (duration.count() * 1e-3) << " ms";
0029 m_logger->log(m_lvl, oss.str());
0030 }
0031 }
0032
0033 AveragingScopedTimer::AveragingScopedTimer(const std::string& name,
0034 const Logger& logger,
0035 Logging::Level lvl)
0036 : m_name(name), m_lvl(lvl), m_logger(&logger) {}
0037
0038 void AveragingScopedTimer::addSample(std::chrono::nanoseconds duration) {
0039 m_sumDuration += duration.count();
0040 m_sumDurationSquared += duration.count() * duration.count();
0041 m_nSamples++;
0042 }
0043
0044 AveragingScopedTimer::Sample::Sample(AveragingScopedTimer& parent)
0045 : m_parent(&parent), m_start(clock_type::now()) {}
0046
0047 AveragingScopedTimer::Sample::Sample(Sample&& other) noexcept
0048 : m_parent(other.m_parent), m_start(other.m_start) {
0049
0050 other.m_parent = nullptr;
0051 }
0052
0053 AveragingScopedTimer::Sample AveragingScopedTimer::sample() {
0054 return Sample{*this};
0055 }
0056
0057 AveragingScopedTimer::Sample::~Sample() {
0058
0059 if (m_parent != nullptr) {
0060 auto end = clock_type::now();
0061 auto duration =
0062 std::chrono::duration_cast<std::chrono::nanoseconds>(end - m_start);
0063 m_parent->addSample(duration);
0064 }
0065 }
0066
0067 AveragingScopedTimer::~AveragingScopedTimer() {
0068 if (m_logger->doPrint(m_lvl)) {
0069 std::ostringstream oss;
0070 if (m_nSamples > 0) {
0071 double mean = m_sumDuration / m_nSamples;
0072 double stddev =
0073 std::sqrt(m_sumDurationSquared / m_nSamples - mean * mean);
0074 oss << m_name << " took " << (m_sumDuration * 1e-6) << " ms total, "
0075 << (mean * 1e-3) << " us +- " << (stddev * 1e-3)
0076 << " us per sample (#" << m_nSamples << ")";
0077 } else {
0078 oss << m_name << " took " << (m_sumDuration * 1e-6)
0079 << " ms total (no samples)";
0080 }
0081 m_logger->log(m_lvl, oss.str());
0082 }
0083 }
0084
0085 }