Pyrogenesis HEAD
Pyrogenesis, a RTS Engine
Profiler2.h
Go to the documentation of this file.
1/* Copyright (C) 2026 Wildfire Games.
2 *
3 * Permission is hereby granted, free of charge, to any person obtaining
4 * a copy of this software and associated documentation files (the
5 * "Software"), to deal in the Software without restriction, including
6 * without limitation the rights to use, copy, modify, merge, publish,
7 * distribute, sublicense, and/or sell copies of the Software, and to
8 * permit persons to whom the Software is furnished to do so, subject to
9 * the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included
12 * in all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 */
22
23/**
24 * @file
25 * New profiler (complementing the older CProfileManager)
26 *
27 * The profiler is designed for analysing framerate fluctuations or glitches,
28 * and temporal relationships between threads.
29 * This contrasts with CProfilerManager and most external profiling tools,
30 * which are designed more for measuring average throughput over a number of
31 * frames.
32 *
33 * To view the profiler output, press F11 to enable the HTTP output mode
34 * and then open source/tools/profiler2/profiler2.html in a web browser.
35 *
36 * There is a single global CProfiler2 instance (g_Profiler2),
37 * providing the API used by the rest of the game.
38 * The game can record the entry/exit timings of a region of code
39 * using the PROFILE2 macro, and can record other events using
40 * PROFILE2_EVENT.
41 * Regions and events can be annotated with arbitrary string attributes,
42 * specified with printf-style format strings, using PROFILE2_ATTR
43 * (e.g. PROFILE2_ATTR("frame: %d", m_FrameNum) ).
44 *
45 * This is designed for relatively coarse-grained profiling, or for rare events.
46 * Don't use it for regions that are typically less than ~0.1msecs, or that are
47 * called hundreds of times per frame. (The old CProfilerManager is better
48 * for that.)
49 *
50 * New threads must call g_Profiler2.RegisterCurrentThread before any other
51 * profiler functions.
52 *
53 * The main thread should call g_Profiler2.RecordFrameStart at the start of
54 * each frame.
55 * Other threads should call g_Profiler2.RecordSyncMarker occasionally,
56 * especially if it's been a long time since their last call to the profiler,
57 * or if they've made thousands of calls since the last sync marker.
58 *
59 * The profiler is implemented with thread-local fixed-size ring buffers,
60 * which store a sequence of variable-length items indicating the time
61 * of the event and associated data (pointers to names, attribute strings, etc).
62 * An HTTP server provides access to the data: when requested, it will make
63 * a copy of a thread's buffer, then parse the items and return them in JSON
64 * format. The profiler2.html requests and processes and visualises this data.
65 *
66 * The RecordSyncMarker calls are necessary to correct for time drift and to
67 * let the buffer parser accurately detect the start of an item in the byte stream.
68 *
69 * This design aims to minimise the performance overhead of recording data,
70 * and to simplify the visualisation of the data by doing it externally in an
71 * environment with better UI tools (i.e. HTML) instead of within the game engine.
72 *
73 * The initial setup of g_Profiler2 must happen in the game's main thread.
74 * RegisterCurrentThread and the Record functions may be called from any thread.
75 * The HTTP server runs its own threads, which may call the ConstructJSON functions.
76 */
77
78#ifndef INCLUDED_PROFILER2
79#define INCLUDED_PROFILER2
80
81#include "lib/code_annotation.h"
82#include "lib/debug.h"
83#include "lib/timer.h"
84#include "ps/ThreadUtil.h"
85
86#include <atomic>
87#include <cstdarg>
88#include <cstring>
89#include <iosfwd>
90#include <memory>
91#include <mutex>
92#include <string>
93#include <thread>
94#include <vector>
95
96class CProfiler2GPU;
97namespace Renderer::Backend { class IDeviceCommandContext; }
98namespace httplib { class Server; }
99
100// Note: Lots of functions are defined inline, to hypothetically
101// minimise performance overhead.
102
104{
105 friend class CProfiler2GPUImpl;
106public:
107 // Items stored in the buffers:
108
109 /// Item type identifiers
110 enum EItem
111 {
113 ITEM_SYNC = 1, // magic value used for parse syncing
114 ITEM_EVENT = 2, // single event
115 ITEM_ENTER = 3, // entering a region
116 ITEM_LEAVE = 4, // leaving a region (must be correctly nested)
117 ITEM_ATTRIBUTE = 5, // arbitrary string associated with current region, or latest event (if the previous item was an event)
118 };
119
120 static const size_t MAX_ATTRIBUTE_LENGTH; // includes null terminator, which isn't stored
121
122 /// An arbitrary number to help resyncing with the item stream when parsing.
123 static const std::uint8_t RESYNC_MAGIC[8];
124
125 /**
126 * An item with a relative time and an ID string pointer.
127 */
129 {
130 float dt; // time relative to last event
131 const char* id;
132 };
133
134private:
135 // TODO: different threads might want different sizes
136 static const size_t BUFFER_SIZE;
137 static const size_t HOLD_BUFFER_SIZE;
138
139 /**
140 * Class instantiated in every registered thread.
141 */
143 {
145 public:
146 ThreadStorage(CProfiler2& profiler, const std::string& name);
148
149 void RecordSyncMarker(double t)
150 {
151 // Store the magic string followed by the absolute time
152 // (to correct for drift caused by the precision of relative
153 // times stored in other items)
154 std::uint8_t buffer[sizeof(RESYNC_MAGIC) + sizeof(t)];
155 memcpy(buffer, &RESYNC_MAGIC, sizeof(RESYNC_MAGIC));
156 memcpy(buffer + sizeof(RESYNC_MAGIC), &t, sizeof(t));
157 Write(ITEM_SYNC, buffer, ARRAY_SIZE(buffer));
158 m_LastTime = t;
159 }
160
161 void Record(EItem type, double t, const char* id)
162 {
163 // Store a relative time instead of absolute, so we can use floats
164 // (to save memory) without suffering from precision problems
165 SItem_dt_id item = { (float)(t - m_LastTime), id };
166 Write(type, &item, sizeof(item));
167 }
168
169 void RecordFrameStart(double t)
170 {
172 Record(ITEM_EVENT, t, "__framestart"); // magic string recognised by the visualiser
173 }
174
175 void RecordLeave(double t)
176 {
177 float time = (float)(t - m_LastTime);
178 Write(ITEM_LEAVE, &time, sizeof(float));
179 }
180
181 void RecordAttribute(const char* fmt, va_list argp) VPRINTF_ARGS(2);
182
183 void RecordAttributePrintf(const char* fmt, ...) PRINTF_ARGS(2)
184 {
185 va_list argp;
186 va_start(argp, fmt);
187 RecordAttribute(fmt, argp);
188 va_end(argp);
189 }
190
192 {
193 return m_Profiler;
194 }
195
196 const std::string& GetName()
197 {
198 return m_Name;
199 }
200
201 /**
202 * Returns a copy of a subset of the thread's buffer.
203 * Not guaranteed to start on an item boundary.
204 * May be called by any thread.
205 */
206 std::string GetBuffer();
207
208 private:
209 /**
210 * Store an item into the buffer.
211 */
212 void Write(EItem type, const void* item, std::uint32_t itemSize);
213
214 void WriteHold(EItem type, const void* item, std::uint32_t itemSize);
215
217 std::string m_Name;
218
219 double m_LastTime; // used for computing relative times
220
221 std::uint8_t* m_Buffer;
222
223 // To allow hopefully-safe reading of the buffer from a separate thread,
224 // without any expensive synchronisation in the recording thread,
225 // two copies of the current buffer write position are stored.
226 // begin is updated before writing; end is updated after writing.
227 // GetBuffer can load end, copy the buffer, load begin, then assume any bytes
228 // outside the range end <= x < begin are safe to use. (Any in that range might
229 // be half-written and corrupted.) (All ranges are modulo BUFFER_SIZE.)
230 // Outside of Write(), these will always be equal.
231
233 {
234 std::atomic<std::uint32_t> begin{0};
235 std::atomic<std::uint32_t> end{0};
236 };
238 };
239
240public:
241 CProfiler2();
242 ~CProfiler2();
243
244 /**
245 * Call in main thread to set up the profiler,
246 * before calling any other profiler functions.
247 */
248 void Initialise();
249
250 /**
251 * Call in main thread to enable the HTTP server.
252 * (Disabled by default for security and performance
253 * and to avoid annoying a firewall.)
254 */
255 void EnableHTTP();
256
257 /**
258 * Call in main thread to enable the GPU profiling support,
259 * after OpenGL has been initialised.
260 */
261 void EnableGPU();
262
263 /**
264 * Call in main thread to shut down the GPU profiling support,
265 * before shutting down OpenGL.
266 */
267 void ShutdownGPU();
268
269 /**
270 * Call in main thread to shut down the profiler's HTTP server
271 */
272 void ShutDownHTTP();
273
274 /**
275 * Call in main thread to enable/disable the profiler
276 */
277 void Toggle();
278
279 /**
280 * Call in main thread to shut everything down.
281 * All other profiled threads should have been terminated already.
282 */
283 void Shutdown();
284
285 /**
286 * Call in any thread to enable the profiler in that thread.
287 * @p name should be unique, and is used by the visualiser to identify
288 * this thread.
289 */
290 void RegisterCurrentThread(const std::string& name);
291
292 /**
293 * Non-main threads should call this occasionally,
294 * especially if it's been a long time since their last call to the profiler,
295 * or if they've made thousands of calls since the last sync marker.
296 */
298 {
300 }
301
302 /**
303 * Call in main thread at the start of a frame.
304 */
306 {
309 }
310
311 void RecordEvent(const char* id)
312 {
314 }
315
316 void RecordRegionEnter(const char* id)
317 {
319 }
320
321 void RecordRegionEnter(const char* id, double time)
322 {
324 }
325
327 {
329 }
330
331 void RecordAttribute(const char* fmt, ...) PRINTF_ARGS(2)
332 {
333 va_list argp;
334 va_start(argp, fmt);
336 va_end(argp);
337 }
338
341 void RecordGPURegionEnter(Renderer::Backend::IDeviceCommandContext* deviceCommandContext, const char* id);
342 void RecordGPURegionLeave(Renderer::Backend::IDeviceCommandContext* deviceCommandContext, const char* id);
343
344 /**
345 * Call in any thread to produce a JSON representation of the general
346 * state of the application.
347 */
348 void ConstructJSONOverview(std::ostream& stream);
349
350 /**
351 * Call in any thread to produce a JSON representation of the buffer
352 * for a given thread.
353 * Returns NULL on success, or an error string.
354 */
355 const char* ConstructJSONResponse(std::ostream& stream, const std::string& thread);
356
357 /**
358 * Call in any thread to save a JSONP representation of the buffers
359 * for all threads, to a file named profile2.jsonp in the logs directory.
360 */
361 void SaveToFile();
362
363 double GetTime()
364 {
365 return timer_Time();
366 }
367
369 {
370 return m_FrameNumber;
371 }
372
374 {
376 }
377
378 void AddThreadStorage(ThreadStorage* storage);
379 void RemoveThreadStorage(ThreadStorage* storage);
380
381private:
382 void InitialiseGPU();
383
385 {
387 return *m_CurrentStorage;
388 }
389
391
393
394 std::unique_ptr<httplib::Server> m_HttpServer;
396
398
399 std::mutex m_Mutex;
400
401 static thread_local ThreadStorage* m_CurrentStorage;
402 std::vector<std::unique_ptr<ThreadStorage>> m_Threads; // thread-safe; protected by m_Mutex
403};
404
406
407/**
408 * Scope-based enter/leave helper.
409 */
411{
412public:
413 CProfile2Region(const char* name) : m_Name(name)
414 {
416 }
418 {
420 }
421protected:
422 const char* m_Name;
423};
424
425/**
426 * Scope-based GPU enter/leave helper.
427 */
429{
430public:
431 CProfile2GPURegion(Renderer::Backend::IDeviceCommandContext* deviceCommandContext, const char* name)
432 : m_DeviceCommandContext(deviceCommandContext), m_Name(name)
433 {
435 }
437 {
439 }
440private:
442 const char* m_Name;
443};
444
445/**
446 * Starts timing from now until the end of the current scope.
447 * @p region is the name to associate with this region (should be
448 * a constant string literal; the pointer must remain valid forever).
449 * Regions may be nested, but preferably shouldn't be nested deeply since
450 * it hurts the visualisation.
451 */
452#define PROFILE2(region) CProfile2Region profile2__(region)
453
454#define PROFILE2_GPU(deviceCommandContext, region) CProfile2GPURegion profile2gpu__(deviceCommandContext, region)
455
456/**
457 * Record the named event at the current time.
458 */
459#define PROFILE2_EVENT(name) g_Profiler2.RecordEvent(name)
460
461/**
462 * Associates a string (with printf-style formatting) with the current
463 * region or event.
464 * (If the last profiler call was PROFILE2_EVENT, it associates with that
465 * event; otherwise it associates with the currently-active region.)
466 */
467#define PROFILE2_ATTR g_Profiler2.RecordAttribute
468
469#endif // INCLUDED_PROFILER2
CProfiler2 g_Profiler2
Definition: Profiler2.cpp:54
Scope-based GPU enter/leave helper.
Definition: Profiler2.h:429
Renderer::Backend::IDeviceCommandContext * m_DeviceCommandContext
Definition: Profiler2.h:441
const char * m_Name
Definition: Profiler2.h:442
~CProfile2GPURegion()
Definition: Profiler2.h:436
CProfile2GPURegion(Renderer::Backend::IDeviceCommandContext *deviceCommandContext, const char *name)
Definition: Profiler2.h:431
Scope-based enter/leave helper.
Definition: Profiler2.h:411
~CProfile2Region()
Definition: Profiler2.h:417
CProfile2Region(const char *name)
Definition: Profiler2.h:413
const char * m_Name
Definition: Profiler2.h:422
At each enter/leave-region event, we do an async GPU timestamp query.
Definition: Profiler2GPU.cpp:47
Used by CProfiler2 for GPU profiling support.
Definition: Profiler2GPU.h:35
Class instantiated in every registered thread.
Definition: Profiler2.h:143
void RecordAttributePrintf(const char *fmt,...) PRINTF_ARGS(2)
Definition: Profiler2.h:183
const std::string & GetName()
Definition: Profiler2.h:196
double m_LastTime
Definition: Profiler2.h:219
~ThreadStorage()
Definition: Profiler2.cpp:264
void Record(EItem type, double t, const char *id)
Definition: Profiler2.h:161
void WriteHold(EItem type, const void *item, std::uint32_t itemSize)
std::string m_Name
Definition: Profiler2.h:217
CProfiler2 & m_Profiler
Definition: Profiler2.h:216
std::string GetBuffer()
Returns a copy of a subset of the thread's buffer.
Definition: Profiler2.cpp:297
void Write(EItem type, const void *item, std::uint32_t itemSize)
Store an item into the buffer.
Definition: Profiler2.cpp:269
RingBufferSpan m_ValidRange
Definition: Profiler2.h:237
void RecordSyncMarker(double t)
Definition: Profiler2.h:149
std::uint8_t * m_Buffer
Definition: Profiler2.h:221
CProfiler2 & GetProfiler()
Definition: Profiler2.h:191
void RecordAttribute(const char *fmt, va_list argp) VPRINTF_ARGS(2)
Definition: Profiler2.cpp:319
NONCOPYABLE(ThreadStorage)
void RecordLeave(double t)
Definition: Profiler2.h:175
ThreadStorage(CProfiler2 &profiler, const std::string &name)
Definition: Profiler2.cpp:257
void RecordFrameStart(double t)
Definition: Profiler2.h:169
Definition: Profiler2.h:104
void RegisterCurrentThread(const std::string &name)
Call in any thread to enable the profiler in that thread.
Definition: Profiler2.cpp:231
void EnableHTTP()
Call in main thread to enable the HTTP server.
Definition: Profiler2.cpp:91
void AddThreadStorage(ThreadStorage *storage)
Definition: Profiler2.cpp:245
void RemoveThreadStorage(ThreadStorage *storage)
Definition: Profiler2.cpp:251
void ConstructJSONOverview(std::ostream &stream)
Call in any thread to produce a JSON representation of the general state of the application.
Definition: Profiler2.cpp:579
bool m_Initialised
Definition: Profiler2.h:390
static const size_t BUFFER_SIZE
Definition: Profiler2.h:136
static thread_local ThreadStorage * m_CurrentStorage
Definition: Profiler2.h:401
static const size_t MAX_ATTRIBUTE_LENGTH
Definition: Profiler2.h:120
void Shutdown()
Call in main thread to shut everything down.
Definition: Profiler2.cpp:194
void RecordGPUFrameStart(Renderer::Backend::IDeviceCommandContext *deviceCommandContext)
Definition: Profiler2.cpp:207
int m_FrameNumber
Definition: Profiler2.h:392
~CProfiler2()
Definition: Profiler2.cpp:71
void RecordRegionEnter(const char *id)
Definition: Profiler2.h:316
void RecordFrameStart()
Call in main thread at the start of a frame.
Definition: Profiler2.h:305
void ShutdownGPU()
Call in main thread to shut down the GPU profiling support, before shutting down OpenGL.
Definition: Profiler2.cpp:155
void EnableGPU()
Call in main thread to enable the GPU profiling support, after OpenGL has been initialised.
Definition: Profiler2.cpp:145
CProfiler2()
Definition: Profiler2.cpp:66
void RecordRegionEnter(const char *id, double time)
Definition: Profiler2.h:321
static const size_t HOLD_BUFFER_SIZE
Definition: Profiler2.h:137
void IncrementFrameNumber()
Definition: Profiler2.h:373
std::vector< std::unique_ptr< ThreadStorage > > m_Threads
Definition: Profiler2.h:402
static const std::uint8_t RESYNC_MAGIC[8]
An arbitrary number to help resyncing with the item stream when parsing.
Definition: Profiler2.h:123
void ShutDownHTTP()
Call in main thread to shut down the profiler's HTTP server.
Definition: Profiler2.cpp:161
void RecordAttribute(const char *fmt,...) PRINTF_ARGS(2)
Definition: Profiler2.h:331
int GetFrameNumber()
Definition: Profiler2.h:368
double GetTime()
Definition: Profiler2.h:363
ThreadStorage & GetThreadStorage()
Definition: Profiler2.h:384
void SaveToFile()
Call in any thread to save a JSONP representation of the buffers for all threads, to a file named pro...
Definition: Profiler2.cpp:788
void RecordGPUFrameEnd(Renderer::Backend::IDeviceCommandContext *deviceCommandContext)
Definition: Profiler2.cpp:213
void Toggle()
Call in main thread to enable/disable the profiler.
Definition: Profiler2.cpp:175
void Initialise()
Call in main thread to set up the profiler, before calling any other profiler functions.
Definition: Profiler2.cpp:77
std::thread m_HttpServerThread
Definition: Profiler2.h:395
const char * ConstructJSONResponse(std::ostream &stream, const std::string &thread)
Call in any thread to produce a JSON representation of the buffer for a given thread.
Definition: Profiler2.cpp:755
void RecordSyncMarker()
Non-main threads should call this occasionally, especially if it's been a long time since their last ...
Definition: Profiler2.h:297
void RecordEvent(const char *id)
Definition: Profiler2.h:311
void RecordGPURegionEnter(Renderer::Backend::IDeviceCommandContext *deviceCommandContext, const char *id)
Definition: Profiler2.cpp:219
void RecordRegionLeave()
Definition: Profiler2.h:326
EItem
Item type identifiers.
Definition: Profiler2.h:111
@ ITEM_SYNC
Definition: Profiler2.h:113
@ ITEM_ENTER
Definition: Profiler2.h:115
@ ITEM_EVENT
Definition: Profiler2.h:114
@ ITEM_LEAVE
Definition: Profiler2.h:116
@ ITEM_NOP
Definition: Profiler2.h:112
@ ITEM_ATTRIBUTE
Definition: Profiler2.h:117
void InitialiseGPU()
Definition: Profiler2.cpp:85
std::unique_ptr< httplib::Server > m_HttpServer
Definition: Profiler2.h:394
std::mutex m_Mutex
Definition: Profiler2.h:399
CProfiler2GPU * m_GPU
Definition: Profiler2.h:397
void RecordGPURegionLeave(Renderer::Backend::IDeviceCommandContext *deviceCommandContext, const char *id)
Definition: Profiler2.cpp:225
Definition: IDeviceCommandContext.h:46
#define PRINTF_ARGS(fmtpos)
Definition: code_annotation.h:213
#define VPRINTF_ARGS(fmtpos)
Definition: code_annotation.h:214
#define ARRAY_SIZE(name)
Definition: code_annotation.h:283
#define ENSURE(expr)
ensure the expression <expr> evaluates to non-zero.
Definition: debug.h:222
Definition: Canvas2D.h:30
bool IsMainThread()
Returns whether the current thread is the 'main' thread (i.e.
Definition: Threading.cpp:29
Definition: HttpServer.h:23
An item with a relative time and an ID string pointer.
Definition: Profiler2.h:129
const char * id
Definition: Profiler2.h:131
float dt
Definition: Profiler2.h:130
std::atomic< std::uint32_t > end
Definition: Profiler2.h:235
std::atomic< std::uint32_t > begin
Definition: Profiler2.h:234
double timer_Time()
Definition: timer.cpp:132