LCOV - code coverage report
Current view: top level - source/ps - Profiler2.h (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 42 70 60.0 %
Date: 2026-12-03 01:19:39 Functions: 6 9 66.7 %

          Line data    Source code
       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             : 
      96             : class CProfiler2GPU;
      97             : namespace Renderer::Backend { class IDeviceCommandContext; }
      98             : namespace httplib { class Server; }
      99             : 
     100             : // Note: Lots of functions are defined inline, to hypothetically
     101             : // minimise performance overhead.
     102             : 
     103             : class CProfiler2
     104             : {
     105             :     friend class CProfiler2GPUImpl;
     106             : public:
     107             :     // Items stored in the buffers:
     108             : 
     109             :     /// Item type identifiers
     110             :     enum EItem
     111             :     {
     112             :         ITEM_NOP = 0,
     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             :      */
     128             :     struct SItem_dt_id
     129             :     {
     130             :         float dt; // time relative to last event
     131             :         const char* id;
     132             :     };
     133             : 
     134             : private:
     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             :      */
     142             :     class ThreadStorage
     143             :     {
     144             :         NONCOPYABLE(ThreadStorage);
     145             :     public:
     146             :         ThreadStorage(CProfiler2& profiler, const std::string& name);
     147             :         ~ThreadStorage();
     148             : 
     149           4 :         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           4 :             std::uint8_t buffer[sizeof(RESYNC_MAGIC) + sizeof(t)];
     155           4 :             memcpy(buffer, &RESYNC_MAGIC, sizeof(RESYNC_MAGIC));
     156           4 :             memcpy(buffer + sizeof(RESYNC_MAGIC), &t, sizeof(t));
     157           4 :             Write(ITEM_SYNC, buffer, ARRAY_SIZE(buffer));
     158           4 :             m_LastTime = t;
     159             :         }
     160             : 
     161       12004 :         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       12004 :             SItem_dt_id item = { (float)(t - m_LastTime), id };
     166       12004 :             Write(type, &item, sizeof(item));
     167           0 :         }
     168             : 
     169           0 :         void RecordFrameStart(double t)
     170             :         {
     171           0 :             RecordSyncMarker(t);
     172           0 :             Record(ITEM_EVENT, t, "__framestart"); // magic string recognised by the visualiser
     173           0 :         }
     174             : 
     175       12001 :         void RecordLeave(double t)
     176             :         {
     177       12001 :             float time = (float)(t - m_LastTime);
     178       12001 :             Write(ITEM_LEAVE, &time, sizeof(float));
     179           0 :         }
     180             : 
     181             :         void RecordAttribute(const char* fmt, va_list argp) VPRINTF_ARGS(2);
     182             : 
     183           0 :         void RecordAttributePrintf(const char* fmt, ...) PRINTF_ARGS(2)
     184             :         {
     185           0 :             va_list argp;
     186           0 :             va_start(argp, fmt);
     187           0 :             RecordAttribute(fmt, argp);
     188           0 :             va_end(argp);
     189           0 :         }
     190             : 
     191             :         CProfiler2& GetProfiler()
     192             :         {
     193             :             return m_Profiler;
     194             :         }
     195             : 
     196           0 :         const std::string& GetName()
     197             :         {
     198           0 :             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             : 
     216             :         CProfiler2& m_Profiler;
     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             : 
     232           4 :         struct RingBufferSpan
     233             :         {
     234             :             std::atomic<std::uint32_t> begin{0};
     235             :             std::atomic<std::uint32_t> end{0};
     236             :         };
     237             :         RingBufferSpan m_ValidRange;
     238             :     };
     239             : 
     240             : public:
     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             :      */
     297           4 :     void RecordSyncMarker()
     298             :     {
     299           8 :         GetThreadStorage().RecordSyncMarker(GetTime());
     300           4 :     }
     301             : 
     302             :     /**
     303             :      * Call in main thread at the start of a frame.
     304             :      */
     305           0 :     void RecordFrameStart()
     306             :     {
     307           0 :         ENSURE(Threading::IsMainThread());
     308           0 :         GetThreadStorage().RecordFrameStart(GetTime());
     309           0 :     }
     310             : 
     311           4 :     void RecordEvent(const char* id)
     312             :     {
     313           8 :         GetThreadStorage().Record(ITEM_EVENT, GetTime(), id);
     314           4 :     }
     315             : 
     316       12000 :     void RecordRegionEnter(const char* id)
     317             :     {
     318       24000 :         GetThreadStorage().Record(ITEM_ENTER, GetTime(), id);
     319       12001 :     }
     320             : 
     321             :     void RecordRegionEnter(const char* id, double time)
     322             :     {
     323             :         GetThreadStorage().Record(ITEM_ENTER, time, id);
     324             :     }
     325             : 
     326       11998 :     void RecordRegionLeave()
     327             :     {
     328       23999 :         GetThreadStorage().RecordLeave(GetTime());
     329       12001 :     }
     330             : 
     331         349 :     void RecordAttribute(const char* fmt, ...) PRINTF_ARGS(2)
     332             :     {
     333         349 :         va_list argp;
     334         349 :         va_start(argp, fmt);
     335         349 :         GetThreadStorage().RecordAttribute(fmt, argp);
     336         349 :         va_end(argp);
     337         349 :     }
     338             : 
     339             :     void RecordGPUFrameStart(Renderer::Backend::IDeviceCommandContext* deviceCommandContext);
     340             :     void RecordGPUFrameEnd(Renderer::Backend::IDeviceCommandContext* deviceCommandContext);
     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       24007 :     double GetTime()
     364             :     {
     365       24007 :         return timer_Time();
     366             :     }
     367             : 
     368           0 :     int GetFrameNumber()
     369             :     {
     370           0 :         return m_FrameNumber;
     371             :     }
     372             : 
     373           0 :     void IncrementFrameNumber()
     374             :     {
     375           0 :         ++m_FrameNumber;
     376             :     }
     377             : 
     378             :     void AddThreadStorage(ThreadStorage* storage);
     379             :     void RemoveThreadStorage(ThreadStorage* storage);
     380             : 
     381             : private:
     382             :     void InitialiseGPU();
     383             : 
     384       24355 :     ThreadStorage& GetThreadStorage()
     385             :     {
     386       24355 :         ENSURE(m_CurrentStorage);
     387           8 :         return *m_CurrentStorage;
     388             :     }
     389             : 
     390             :     bool m_Initialised;
     391             : 
     392             :     int m_FrameNumber;
     393             : 
     394             :     std::unique_ptr<httplib::Server> m_HttpServer;
     395             :     std::thread m_HttpServerThread;
     396             : 
     397             :     CProfiler2GPU* m_GPU;
     398             : 
     399             :     std::mutex m_Mutex;
     400             : 
     401       48694 :     static thread_local ThreadStorage* m_CurrentStorage;
     402             :     std::vector<std::unique_ptr<ThreadStorage>> m_Threads; // thread-safe; protected by m_Mutex
     403             : };
     404             : 
     405             : extern CProfiler2 g_Profiler2;
     406             : 
     407             : /**
     408             :  * Scope-based enter/leave helper.
     409             :  */
     410             : class CProfile2Region
     411             : {
     412             : public:
     413       11437 :     CProfile2Region(const char* name) : m_Name(name)
     414             :     {
     415       11437 :         g_Profiler2.RecordRegionEnter(m_Name);
     416        3548 :     }
     417       11434 :     ~CProfile2Region()
     418             :     {
     419       11434 :         g_Profiler2.RecordRegionLeave();
     420             :     }
     421             : protected:
     422             :     const char* m_Name;
     423             : };
     424             : 
     425             : /**
     426             :  * Scope-based GPU enter/leave helper.
     427             :  */
     428             : class CProfile2GPURegion
     429             : {
     430             : public:
     431           0 :     CProfile2GPURegion(Renderer::Backend::IDeviceCommandContext* deviceCommandContext, const char* name)
     432           0 :         : m_DeviceCommandContext(deviceCommandContext), m_Name(name)
     433             :     {
     434           0 :         g_Profiler2.RecordGPURegionEnter(m_DeviceCommandContext, m_Name);
     435           0 :     }
     436           0 :     ~CProfile2GPURegion()
     437             :     {
     438           0 :         g_Profiler2.RecordGPURegionLeave(m_DeviceCommandContext, m_Name);
     439             :     }
     440             : private:
     441             :     Renderer::Backend::IDeviceCommandContext* m_DeviceCommandContext;
     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

Generated by: LCOV version 1.16