ClickHouse/src/Common/ProfileEvents.h

116 lines
3.0 KiB
C++
Raw Normal View History

#pragma once
#include <Common/VariableContext.h>
2016-07-31 03:53:16 +00:00
#include <atomic>
#include <memory>
#include <stddef.h>
/** Implements global counters for various events happening in the application
* - for high level profiling.
* See .cpp for list of events.
*/
namespace ProfileEvents
{
/// Event identifier (index in array).
using Event = size_t;
using Count = size_t;
using Counter = std::atomic<Count>;
class Counters;
/// Counters - how many times each event happened
extern Counters global_counters;
class Counters
{
Counter * counters = nullptr;
std::unique_ptr<Counter[]> counters_holder;
/// Used to propagate increments
Counters * parent = nullptr;
public:
VariableContext level = VariableContext::Thread;
/// By default, any instance have to increment global counters
2019-08-03 11:02:40 +00:00
Counters(VariableContext level_ = VariableContext::Thread, Counters * parent_ = &global_counters);
/// Global level static initializer
2020-03-18 03:27:32 +00:00
Counters(Counter * allocated_counters) noexcept
2018-11-26 00:56:50 +00:00
: counters(allocated_counters), parent(nullptr), level(VariableContext::Global) {}
Counter & operator[] (Event event)
{
return counters[event];
}
const Counter & operator[] (Event event) const
{
return counters[event];
}
inline void increment(Event event, Count amount = 1)
{
Counters * current = this;
do
{
current->counters[event].fetch_add(amount, std::memory_order_relaxed);
current = current->parent;
} while (current != nullptr);
}
struct Snapshot
{
Snapshot();
Count & operator[] (Event event)
{
return counters_holder[event];
}
const Count & operator[] (Event event) const
{
return counters_holder[event];
}
private:
std::unique_ptr<Count[]> counters_holder;
};
2018-08-17 18:57:07 +00:00
/// Every single value is fetched atomically, but not all values as a whole.
Snapshot getPartiallyAtomicSnapshot() const;
2018-08-17 18:57:07 +00:00
/// Reset all counters to zero and reset parent.
void reset();
/// Get parent (thread unsafe)
Counters * getParent()
{
return parent;
}
2018-05-29 18:14:31 +00:00
/// Set parent (thread unsafe)
void setParent(Counters * parent_)
{
parent = parent_;
}
/// Set all counters to zero
void resetCounters();
static const Event num_counters;
};
/// Increment a counter for event. Thread-safe.
void increment(Event event, Count amount = 1);
/// Get name of event by identifier. Returns statically allocated string.
const char * getName(Event event);
/// Get description of event by identifier. Returns statically allocated string.
const char * getDocumentation(Event event);
/// Get index just after last event identifier.
Event end();
}