Add ProfileEvents::Timer class

Example of use (assumes we have ProfileEvents::SomethingTimeMilliseconds):

```c++
using ProfileEvents::Timer::Resolution;

...

if (do_something)
{
    counters->timer<Resolution::Milliseconds>(SomethingTimeMilliseconds);
    /// do "something"
} /// timer increments when scope exits

```
This commit is contained in:
Stig Bakken 2023-09-03 13:20:20 +02:00
parent 776f232ec0
commit 3ae835895d
2 changed files with 58 additions and 0 deletions

View File

@ -570,6 +570,23 @@ Counters global_counters(global_counters_array);
const Event Counters::num_counters = END;
Timer::Timer(Counters & counters_, Event timer_event_, Resolution resolution_)
: counters(counters_), timer_event(timer_event_), resolution(resolution_)
{
}
Timer::Timer(Counters & counters_, Event timer_event_, Event counter_event, Resolution resolution_)
: Timer(counters_, timer_event_, resolution_)
{
counters.increment(counter_event);
}
void Timer::end()
{
counters.increment(timer_event, watch.elapsedNanoseconds() / static_cast<UInt64>(resolution));
watch.reset();
}
Counters::Counters(VariableContext level_, Counters * parent_)
: counters_holder(new Counter[num_counters] {}),
parent(parent_),

View File

@ -1,6 +1,7 @@
#pragma once
#include <Common/VariableContext.h>
#include <Common/Stopwatch.h>
#include <base/types.h>
#include <base/strong_typedef.h>
#include <Poco/Message.h>
@ -26,6 +27,28 @@ namespace ProfileEvents
/// Counters - how many times each event happened
extern Counters global_counters;
class Timer
{
public:
enum class Resolution : UInt64
{
Nanoseconds = 1,
Microseconds = 1000,
Milliseconds = 1000000,
};
Timer(Counters & counters_, Event timer_event_, Resolution resolution_);
Timer(Counters & counters_, Event timer_event_, Event counter_event, Resolution resolution_);
~Timer() { end(); }
void cancel() { watch.reset(); }
void end();
private:
Counters & counters;
Event timer_event;
Stopwatch watch;
Resolution resolution;
};
class Counters
{
private:
@ -103,6 +126,24 @@ namespace ProfileEvents
/// Set all counters to zero
void resetCounters();
/// Add elapsed time to `timer_event` when returned object goes out of scope.
/// Use the template parameter to control timer resolution, the default
/// is `Timer::Resolution::Microseconds`.
template <Timer::Resolution resolution = Timer::Resolution::Microseconds>
Timer timer(Event timer_event)
{
return Timer(*this, timer_event, resolution);
}
/// Increment `counter_event` and add elapsed time to `timer_event` when returned object goes out of scope.
/// Use the template parameter to control timer resolution, the default
/// is `Timer::Resolution::Microseconds`.
template <Timer::Resolution resolution = Timer::Resolution::Microseconds>
Timer timer(Event timer_event, Event counter_event)
{
return Timer(*this, timer_event, counter_event, resolution);
}
static const Event num_counters;
};