diff --git a/include/ProfilerLib/Profiler.hpp b/include/ProfilerLib/Profiler.hpp index f236241..15a15ee 100644 --- a/include/ProfilerLib/Profiler.hpp +++ b/include/ProfilerLib/Profiler.hpp @@ -67,11 +67,16 @@ class Profiler { void disable(); + void enable(); + [[nodiscard]] bool isEnabled() const; - private: void save(); - void submitEvent(const TraceEvent &event); + + private: + // Forcing the event to be submitted causes it to be written even if the profiler is disabled. This is useful when a + // task consists of multiple events (such as scopeevent) where the profiler might be disabled during task execution. + void submitEvent(const TraceEvent &event, bool force = false); std::string name; std::filesystem::path outputPath; diff --git a/include/ProfilerLib/ScopeEvent.hpp b/include/ProfilerLib/ScopeEvent.hpp index 556c333..ac770ae 100644 --- a/include/ProfilerLib/ScopeEvent.hpp +++ b/include/ProfilerLib/ScopeEvent.hpp @@ -30,6 +30,7 @@ class ScopeEvent { ~ScopeEvent(); private: + bool active; Profiler &p; }; diff --git a/src/Profiler.cpp b/src/Profiler.cpp index ab2dfb5..e6eea1a 100644 --- a/src/Profiler.cpp +++ b/src/Profiler.cpp @@ -23,8 +23,8 @@ Profiler::Profiler(std::string name, std::filesystem::path outputPath) : submitInstantEvent("Profiler \"" + this->name + "\" starting", Scope::Global); } -void Profiler::submitEvent(const TraceEvent &event) { - if (!this->enabled) { +void Profiler::submitEvent(const TraceEvent &event, bool force) { + if (!this->enabled && !force) { return; } std::lock_guard lock(eventListMutex); @@ -116,6 +116,10 @@ void Profiler::disable() { this->enabled = false; } +void Profiler::enable() { + this->enabled = true; +} + [[nodiscard]] bool Profiler::isEnabled() const { return enabled; }; diff --git a/src/ProfilerUtil.cpp b/src/ProfilerUtil.cpp index b5cc8db..6bfb5a6 100644 --- a/src/ProfilerUtil.cpp +++ b/src/ProfilerUtil.cpp @@ -22,6 +22,6 @@ namespace profilerUtil { } std::size_t tidHash() { - return std::hash{}(tid()); + return std::hash{}(tid()) & 0xFFFFFFF; } } // namespace profilerUtil diff --git a/src/ScopeEvent.cpp b/src/ScopeEvent.cpp index 6263b99..789b9a5 100644 --- a/src/ScopeEvent.cpp +++ b/src/ScopeEvent.cpp @@ -12,6 +12,10 @@ #include "TraceEvent.hpp" // for TraceEvent, TraceEventType, Trac... ScopeEvent::ScopeEvent(Profiler &profiler, std::string name) : p{profiler} { + active = p.isEnabled(); + if (!active) { + return; + } TraceEvent e; e.ph = TraceEventType::DurationBegin; e.name = p.name + ": " + std::move(name); @@ -19,7 +23,12 @@ ScopeEvent::ScopeEvent(Profiler &profiler, std::string name) : p{profiler} { } ScopeEvent::~ScopeEvent() { + if (!active) { + // Prevent submitting DurationEnd when the profiler was disabled at DurationBegin + return; + } TraceEvent e; e.ph = TraceEventType::DurationEnd; - p.submitEvent(e); + // Submit the event even if profiler was disabled in the meantime (only consider enabled state at start) + p.submitEvent(e, true); }