10#include <unordered_map>
16std::atomic<bool> g_enabled{
false};
19 return std::chrono::duration_cast<std::chrono::nanoseconds>(
20 std::chrono::steady_clock::now().time_since_epoch())
25std::mutex g_modulesMutex;
26std::vector<std::string> g_moduleNames{
""};
27std::unordered_map<std::string, uint32_t> g_moduleIds;
29std::string zoneKey(uint32_t module, uint32_t threadId,
const char*
name) {
30 return std::to_string(module) +
":" + std::to_string(threadId) +
":" + (
name ?
name :
"");
48std::mutex g_threadsMutex;
52 static thread_local ThreadBuffer
tb;
53 if (
tb.threadId == 0) {
54 tb.
threadId =
static_cast<uint32_t
>(std::hash<std::thread::id>{}(std::this_thread::get_id()));
55 std::lock_guard<std::mutex> lock(g_threadsMutex);
56 tb.threadName = threads().empty() ?
"main" :
"worker/" + std::to_string(
tb.threadId);
57 threads().push_back(&
tb);
62std::vector<Profiler::ThreadBuffer*>& Profiler::threads() {
63 static std::vector<ThreadBuffer*>
t;
67Profiler::Frame& Profiler::lastFrameStorage() {
72bool& Profiler::hasFrameFlag() {
73 static bool b =
false;
78 if (!module || !module[0])
return 0;
79 std::lock_guard<std::mutex> lock(g_modulesMutex);
80 auto it = g_moduleIds.find(module);
81 if (it != g_moduleIds.end())
return it->second;
82 const uint32_t
id =
static_cast<uint32_t
>(g_moduleNames.size());
83 g_moduleNames.push_back(module);
84 g_moduleIds.emplace(module,
id);
91 if (on) (void)currentBuffer();
92 g_enabled.store(on, std::memory_order_relaxed);
98 if (!g_enabled.load(std::memory_order_relaxed))
return;
103 r.threadId =
tb.threadId;
104 r.parent =
tb.stack.empty() ? -1 :
tb.stack.back();
105 r.depth =
static_cast<int16_t
>(
tb.stack.size());
109 const int32_t
idx =
static_cast<int32_t
>(
tb.records.size());
110 tb.records.push_back(
r);
111 tb.stack.push_back(
idx);
115 if (!g_enabled.load(std::memory_order_relaxed))
return;
117 if (
tb.stack.empty())
return;
118 const int32_t
idx =
tb.stack.back();
120 tb.records[
static_cast<size_t>(
idx)].endNs = nowNs();
124 std::lock_guard<std::mutex> lock(g_threadsMutex);
125 for (
auto*
tb : threads()) {
129 lastFrameStorage() =
Frame{};
130 hasFrameFlag() =
false;
134 if (!g_enabled.load(std::memory_order_relaxed))
return 0.0;
136 const int64_t t0 = nowNs();
142 std::vector<ZoneRecord> records;
144 std::vector<Snap> snaps;
146 std::lock_guard<std::mutex> lock(g_threadsMutex);
147 for (
auto*
tb : threads()) {
149 s.tid =
tb->threadId;
150 s.tname =
tb->threadName;
151 for (
auto&
r :
tb->records)
152 if (
r.endNs == 0)
r.endNs = t0;
153 s.records = std::move(
tb->records);
156 snaps.push_back(std::move(
s));
163 double totalMs = 0.0;
165 int minDepth = 0x7fffffff;
170 std::unordered_map<std::string, Agg> aggMap;
171 int64_t spanBegin = t0;
172 int64_t spanEnd = t0;
174 for (
const auto&
s : snaps) {
175 const size_t n =
s.records.size();
176 std::vector<int64_t> total(
n, 0);
177 std::vector<int64_t> child(
n, 0);
178 for (
size_t i = 0; i <
n; ++i) {
179 spanBegin = std::min(spanBegin,
s.records[i].startNs);
180 spanEnd = std::max(spanEnd,
s.records[i].endNs);
181 int64_t
t =
s.records[i].endNs -
s.records[i].startNs;
185 for (
size_t i = 0; i <
n; ++i) {
186 const int32_t
p =
s.records[i].parent;
187 if (
p >= 0 &&
p <
static_cast<int32_t
>(
n)) child[
static_cast<size_t>(
p)] += total[i];
189 for (
size_t i = 0; i <
n; ++i) {
190 const auto&
r =
s.records[i];
191 const int64_t self = total[i] - child[i];
192 Agg&
a = aggMap[zoneKey(
r.module,
r.threadId,
r.name)];
193 a.selfMs +=
static_cast<double>(self) / 1'000'000.0;
194 a.totalMs +=
static_cast<double>(total[i]) / 1'000'000.0;
197 a.name =
r.name ?
r.name :
"";
199 if (
r.depth <
a.minDepth)
a.minDepth =
r.depth;
205 for (
auto& kv : aggMap) {
208 sm.module =
a.module < g_moduleNames.size() ? g_moduleNames[
a.module]
209 : std::string(
"default");
216 f.samples.push_back(std::move(sm));
218 std::sort(
f.samples.begin(),
f.samples.end(),
222 lastFrameStorage() = std::move(
f);
223 hasFrameFlag() =
true;
224 return static_cast<double>(nowNs() - t0) / 1'000'000.0;
232 std::vector<ZoneSample>
out;
233 if (!hasFrameFlag() ||
limit == 0)
return out;
234 const auto& samples = lastFrameStorage().
samples;
235 out.reserve(std::min(
limit, samples.size()));
237 if (sample.selfMs < minSelfMs)
continue;
238 out.push_back(sample);
245 if (!hasFrameFlag())
return "=== Profiler: no frame captured yet ===\n";
246 std::ostringstream os;
248 const double totalMs =
249 static_cast<double>(lastFrameStorage().
endNs - lastFrameStorage().
beginNs) / 1'000'000.0;
250 std::snprintf(buf,
sizeof(buf),
"%.2f", totalMs);
251 os <<
"=== Profiler captured CPU span (" << buf <<
" ms) ===\n";
252 os <<
"-- Per-module / per-zone (self time, sorted) --\n";
253 for (
const auto&
s : lastFrameStorage().
samples) {
254 std::snprintf(buf,
sizeof(buf),
"%.3f",
s.selfMs);
255 os <<
" [" <<
s.module <<
"/" <<
s.thread <<
"] " <<
s.name
256 <<
" self=" << buf <<
" ms";
257 std::snprintf(buf,
sizeof(buf),
"%.3f",
s.totalMs);
258 os <<
" total=" << buf <<
" ms";
259 if (
s.count > 1) os <<
" x" <<
s.count;
static std::string textReport()
Human-readable report of the last frame.
static void setEnabled(bool on)
Turns collection on/off globally (off = single-branch no-op).
static const std::vector< ZoneSample > & lastFrame()
Per-module/per-zone samples of the last frame, sorted by self time.
static void zoneBegin(const char *name, const char *module=nullptr)
Opens a scoped zone on the current thread.
static std::vector< ZoneSample > hotspots(std::size_t limit, double minSelfMs)
Copy the hottest zones from the last completed frame.
static double frameMark()
Finalizes the current frame: snapshots all thread buffers and aggregates them into lastFrame().
static void reset()
Clears all collected state.
static uint32_t moduleId(const char *module)
Interns a module name and returns its stable id.
static void zoneEnd()
Closes the innermost open zone on the current thread.
static bool hasFrame()
True once at least one frame has been aggregated.
static bool enabled()
True when collection is active.
std::vector< ZoneSample > samples
std::vector< int32_t > stack
std::vector< ZoneRecord > records
One completed profiling zone (pre-order, parent-linked within a thread).
Per-module/per-zone aggregate of the last completed frame.
std::string std::string name