载入中...
搜索中...
未找到
Profile.cpp
浏览该文件的文档.
1#include "common/Profile.h"
2
3#include <algorithm>
4#include <chrono>
5#include <cstdio>
6#include <cstring>
7#include <mutex>
8#include <sstream>
9#include <thread>
10#include <unordered_map>
11#include <vector>
12
13namespace eve::prof {
14
15namespace {
16std::atomic<bool> g_enabled{false};
17
18int64_t nowNs() {
19 return std::chrono::duration_cast<std::chrono::nanoseconds>(
20 std::chrono::steady_clock::now().time_since_epoch())
21 .count();
22}
23
24// Module id interning (thread-safe).
25std::mutex g_modulesMutex;
26std::vector<std::string> g_moduleNames{""}; // index 0 = "default"
27std::unordered_map<std::string, uint32_t> g_moduleIds;
28
29std::string zoneKey(uint32_t module, uint32_t threadId, const char* name) {
30 return std::to_string(module) + ":" + std::to_string(threadId) + ":" + (name ? name : "");
31}
32} // namespace
33
35 uint32_t threadId = 0;
36 std::string threadName = "main";
37 std::vector<ZoneRecord> records;
38 std::vector<int32_t> stack; // indices of open zones
39};
40
42 int64_t beginNs = 0;
43 int64_t endNs = 0;
44 std::vector<ZoneSample> samples;
45};
46
47namespace {
48std::mutex g_threadsMutex;
49} // namespace
50
51Profiler::ThreadBuffer& Profiler::currentBuffer() {
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);
58 }
59 return tb;
60}
61
62std::vector<Profiler::ThreadBuffer*>& Profiler::threads() {
63 static std::vector<ThreadBuffer*> t;
64 return t;
65}
66
67Profiler::Frame& Profiler::lastFrameStorage() {
68 static Frame f;
69 return f;
70}
71
72bool& Profiler::hasFrameFlag() {
73 static bool b = false;
74 return b;
75}
76
77uint32_t Profiler::moduleId(const char* module) {
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);
85 return id;
86}
87
88// --- public API -------------------------------------------------------------
89
90void Profiler::setEnabled(bool on) {
91 if (on) (void)currentBuffer();
92 g_enabled.store(on, std::memory_order_relaxed);
93}
94
95bool Profiler::enabled() { return g_enabled.load(std::memory_order_relaxed); }
96
97void Profiler::zoneBegin(const char* name, const char* module) {
98 if (!g_enabled.load(std::memory_order_relaxed)) return;
99 ThreadBuffer& tb = currentBuffer();
101 r.name = name ? name : "";
102 r.module = moduleId(module);
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());
106 r.startNs = nowNs();
107 r.endNs = 0;
108 r.kind = 0;
109 const int32_t idx = static_cast<int32_t>(tb.records.size());
110 tb.records.push_back(r);
111 tb.stack.push_back(idx);
112}
113
115 if (!g_enabled.load(std::memory_order_relaxed)) return;
116 ThreadBuffer& tb = currentBuffer();
117 if (tb.stack.empty()) return;
118 const int32_t idx = tb.stack.back();
119 tb.stack.pop_back();
120 tb.records[static_cast<size_t>(idx)].endNs = nowNs();
121}
122
124 std::lock_guard<std::mutex> lock(g_threadsMutex);
125 for (auto* tb : threads()) {
126 tb->records.clear();
127 tb->stack.clear();
128 }
129 lastFrameStorage() = Frame{};
130 hasFrameFlag() = false;
131}
132
134 if (!g_enabled.load(std::memory_order_relaxed)) return 0.0;
135
136 const int64_t t0 = nowNs();
137
138 // Snapshot and clear every thread buffer.
139 struct Snap {
140 uint32_t tid;
141 std::string tname;
142 std::vector<ZoneRecord> records;
143 };
144 std::vector<Snap> snaps;
145 {
146 std::lock_guard<std::mutex> lock(g_threadsMutex);
147 for (auto* tb : threads()) {
148 Snap s;
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);
154 tb->records.clear();
155 tb->stack.clear();
156 snaps.push_back(std::move(s));
157 }
158 }
159
160 // Aggregate per (module, name): self = own total - sum of children totals.
161 struct Agg {
162 double selfMs = 0.0;
163 double totalMs = 0.0;
164 int count = 0;
165 int minDepth = 0x7fffffff;
166 uint32_t module = 0;
167 std::string name;
168 std::string thread;
169 };
170 std::unordered_map<std::string, Agg> aggMap;
171 int64_t spanBegin = t0;
172 int64_t spanEnd = t0;
173
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;
182 if (t < 0) t = 0;
183 total[i] = t;
184 }
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];
188 }
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;
195 ++a.count;
196 a.module = r.module;
197 a.name = r.name ? r.name : "";
198 a.thread = s.tname;
199 if (r.depth < a.minDepth) a.minDepth = r.depth;
200 }
201 }
202
203 Frame f;
204 f.beginNs = spanBegin;
205 for (auto& kv : aggMap) {
206 Agg& a = kv.second;
207 ZoneSample sm;
208 sm.module = a.module < g_moduleNames.size() ? g_moduleNames[a.module]
209 : std::string("default");
210 sm.name = a.name;
211 sm.thread = a.thread;
212 sm.selfMs = a.selfMs;
213 sm.totalMs = a.totalMs;
214 sm.count = a.count;
215 sm.minDepth = a.minDepth;
216 f.samples.push_back(std::move(sm));
217 }
218 std::sort(f.samples.begin(), f.samples.end(),
219 [](const ZoneSample& x, const ZoneSample& y) { return x.selfMs > y.selfMs; });
220 f.endNs = spanEnd;
221
222 lastFrameStorage() = std::move(f);
223 hasFrameFlag() = true;
224 return static_cast<double>(nowNs() - t0) / 1'000'000.0;
225}
226
227bool Profiler::hasFrame() { return hasFrameFlag(); }
228
229const std::vector<ZoneSample>& Profiler::lastFrame() { return lastFrameStorage().samples; }
230
231std::vector<ZoneSample> Profiler::hotspots(std::size_t limit, double minSelfMs) {
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()));
236 for (const ZoneSample& sample : samples) {
237 if (sample.selfMs < minSelfMs) continue;
238 out.push_back(sample);
239 if (out.size() >= limit) break;
240 }
241 return out;
242}
243
244std::string Profiler::textReport() {
245 if (!hasFrameFlag()) return "=== Profiler: no frame captured yet ===\n";
246 std::ostringstream os;
247 char buf[64];
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;
260 os << "\n";
261 }
262 return os.str();
263}
264
265} // namespace eve::prof
double y
double x
const std::string & s
glm::vec4 p[6]
std::string name
Definition ECS.cpp:154
glm::vec3 n
Definition Grass.cpp:63
double r
std::string id
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
float tb
int idx
float f
float t
ScriptStructure out
int count
int limit
Definition TreeMesh.cpp:166
static std::string textReport()
Human-readable report of the last frame.
Definition Profile.cpp:244
static void setEnabled(bool on)
Turns collection on/off globally (off = single-branch no-op).
Definition Profile.cpp:90
static const std::vector< ZoneSample > & lastFrame()
Per-module/per-zone samples of the last frame, sorted by self time.
Definition Profile.cpp:229
static void zoneBegin(const char *name, const char *module=nullptr)
Opens a scoped zone on the current thread.
Definition Profile.cpp:97
static std::vector< ZoneSample > hotspots(std::size_t limit, double minSelfMs)
Copy the hottest zones from the last completed frame.
Definition Profile.cpp:231
static double frameMark()
Finalizes the current frame: snapshots all thread buffers and aggregates them into lastFrame().
Definition Profile.cpp:133
static void reset()
Clears all collected state.
Definition Profile.cpp:123
static uint32_t moduleId(const char *module)
Interns a module name and returns its stable id.
Definition Profile.cpp:77
static void zoneEnd()
Closes the innermost open zone on the current thread.
Definition Profile.cpp:114
static bool hasFrame()
True once at least one frame has been aggregated.
Definition Profile.cpp:227
static bool enabled()
True when collection is active.
Definition Profile.cpp:95
std::vector< ZoneSample > samples
Definition Profile.cpp:44
std::vector< int32_t > stack
Definition Profile.cpp:38
std::vector< ZoneRecord > records
Definition Profile.cpp:37
One completed profiling zone (pre-order, parent-linked within a thread).
Definition Profile.h:36
const char * name
Definition Profile.h:37
Per-module/per-zone aggregate of the last completed frame.
Definition Profile.h:50
std::string thread
Definition Profile.h:53
std::string std::string name
Definition Profile.h:52