From 2b35fb11058ab9cc530413f73aebc842a5c16c20 Mon Sep 17 00:00:00 2001 From: Ben Hoffman Date: Tue, 17 Nov 2026 11:01:06 -0500 Subject: [PATCH 1/2] Instrumented profiler: FLING_PROFILE_SCOPE and --profile A scope times a block on any thread. Scopes with one name add up, with a call count and the slowest call. --profile turns it on and prints a table at exit (works with --null-render, --offscreen and a window). Off, a scope costs one atomic load; shipping builds remove it. Scopes added: the main loop (input, world update, present), the snapshot system, the G-buffer pass steps, the pass recording and the wait for the GPU. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017NN37Q2jpV81xZaX3ocojK --- AGENTS.md | 6 + FlingEngine/Application/src/Engine.cpp | 23 ++- FlingEngine/Core/inc/LaunchOptions.h | 4 + FlingEngine/Core/inc/Profiler.h | 90 ++++++++++ FlingEngine/Core/src/LaunchOptions.cpp | 4 +- FlingEngine/Core/src/Profiler.cpp | 154 ++++++++++++++++++ FlingEngine/Graphics/src/OffscreenSubpass.cpp | 23 ++- .../src/Systems/PublishSnapshotSystem.cpp | 2 + FlingEngine/Graphics/src/VulkanApp.cpp | 16 +- FlingTests/Core/ProfilerTests.cpp | 34 ++++ 10 files changed, 343 insertions(+), 13 deletions(-) create mode 100644 FlingEngine/Core/inc/Profiler.h create mode 100644 FlingEngine/Core/src/Profiler.cpp create mode 100644 FlingTests/Core/ProfilerTests.cpp diff --git a/AGENTS.md b/AGENTS.md index 6d371f9c..bf8c0787 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,6 +62,12 @@ platform setup (Vulkan SDK, GLFW, etc.). module, any thread): `Fling::Screenshot::Request(path, callback)` in `Screenshot.h`; the editor's GPU Options window has a Take screenshot button. Detail: [`Skills/testing.md`](Skills/testing.md#seeing-the-game-without-a-window). +- See where the time goes: add `--profile` to any run (it works with `--null-render`, + `--offscreen` and a window) and a table of timed scopes prints after the exit line. + A scope is `FLING_PROFILE_SCOPE("Name")` from `Profiler.h` (Core): off it costs one + atomic load, and shipping builds remove it. Measure in the build mode you care about: + Debug is much slower than RelWithDebInfo for per-entity work. In a window, use `--play` + (a window without it starts the editor, which runs no ticks). - Drive a headless run with `--replay-input `. Agents can write their own `.input.jsonl` files. Format and flags: [`Skills/input-playback.md`](Skills/input-playback.md). - Load a level other than `[Game] StartLevel` with `--level ` (relative diff --git a/FlingEngine/Application/src/Engine.cpp b/FlingEngine/Application/src/Engine.cpp index 56336fdd..a46c1bd9 100644 --- a/FlingEngine/Application/src/Engine.cpp +++ b/FlingEngine/Application/src/Engine.cpp @@ -15,6 +15,7 @@ #include "Misc/CrashHandler.h" #include "Physics.h" #include "PresentMode.h" +#include "Profiler.h" #include "Random.h" #include "RegisterGraphics.h" #include "Screenshot.h" @@ -582,6 +583,7 @@ namespace Fling // sends the messages of a tick over its N frames const float NullRenderDeltaTime = 1.0f / static_cast(m_Settings.SimHz * m_Options.FramesPerTick); + Profiler::SetEnabled(m_Options.Profile); const std::chrono::steady_clock::time_point LoopStart = std::chrono::steady_clock::now(); while (ShouldTick()) { @@ -591,13 +593,20 @@ namespace Fling // for its ticks, so a run is as fast as the CPU allows const float DeltaTime = m_Options.IsHeadless() ? NullRenderDeltaTime : Timing.GetDeltaTime(); Stats::Frames::FrameStats(DeltaTime); + FLING_PROFILE_SCOPE("Frame"); - PumpInput(DeltaTime); - m_Controls->OnFrame(PlatformTime::NowNanoseconds()); + { + FLING_PROFILE_SCOPE("Frame.Input"); + PumpInput(DeltaTime); + m_Controls->OnFrame(PlatformTime::NowNanoseconds()); + } // The play requests, this frame's ticks (the game thread runs them itself in // threaded play), the ticks' outbox, then the frame systems on what the world shows - m_World->Update(DeltaTime); + { + FLING_PROFILE_SCOPE("Frame.WorldUpdate"); + m_World->Update(DeltaTime); + } DumpNewTicks(); WriteStateDumps(); @@ -705,6 +714,7 @@ namespace Fling // the swap chain again after this frame's present. VulkanApp::Get().SetVSync(m_Controls->VSync()); VulkanApp::Get().SetFrustumCulling(m_Controls->FrustumCulling()); + FLING_PROFILE_SCOPE("Frame.Present"); VulkanApp::Get().Update(t_DeltaTime, m_World->GetPresentedStorage()); // Offscreen there is no window: no focus, no monitor, and no frame cap (headless) @@ -986,6 +996,13 @@ namespace Fling } PrintExitSummary(t_Code); + if (m_Options.Profile) + { + const double WallSeconds = + std::chrono::duration(std::chrono::steady_clock::now() - m_StartTime).count(); + std::printf("%s", Profiler::Report(WallSeconds).c_str()); + std::fflush(stdout); + } // Last, so that every system above can still log while it shuts down Logger::Get().Shutdown(); diff --git a/FlingEngine/Core/inc/LaunchOptions.h b/FlingEngine/Core/inc/LaunchOptions.h index 378500ad..d8ab000d 100644 --- a/FlingEngine/Core/inc/LaunchOptions.h +++ b/FlingEngine/Core/inc/LaunchOptions.h @@ -78,6 +78,7 @@ namespace Fling * --frustum-culling on|off * Skip the meshes outside the camera's view (on) or draw every mesh * (off). Overrides [Engine] FrustumCulling + * --profile Time the FLING_PROFILE_SCOPE scopes and print a table of them at exit * --thread-jitter S:U --exec threaded only: sleep a random 0..U microseconds (seed S) before each wake * and after each publish on the game thread, and before each frame */ @@ -109,6 +110,9 @@ namespace Fling bool Unattended = false; + /** Time the profiled scopes and print the table at exit (--profile). See Profiler.h. */ + bool Profile = false; + /** Number of frames to run before the engine exits (--frames). 0 means no limit. */ uint32 Frames = 0; diff --git a/FlingEngine/Core/inc/Profiler.h b/FlingEngine/Core/inc/Profiler.h new file mode 100644 index 00000000..3dab872e --- /dev/null +++ b/FlingEngine/Core/inc/Profiler.h @@ -0,0 +1,90 @@ +#pragma once + +#include "CoreAPI.h" +#include "FlingTypes.h" +#include "Strings/String.h" + +#include + +namespace Fling +{ + /** + * Instrumented timing for the engine. A FLING_PROFILE_SCOPE("Name") at the top of a + * block times that block, on any thread. Scopes with the same name add up, so a scope in + * a loop shows its total, its call count and its slowest call. + * + * It is off until --profile (or Profiler::SetEnabled) turns it on. An off scope costs one + * relaxed atomic load. An on scope costs two clock reads and three stores into the + * calling thread's own table: no lock, no allocation after the first call on a thread. + * Shipping builds compile every scope out. + * + * Profiler::Report gives the table: Engine prints it at exit with --profile. + */ + class Profiler + { + public: + /** The most scopes (different names) that one run can have. */ + static constexpr uint32 MaxScopes = 256; + + static CORE_API bool IsEnabled(); + static CORE_API void SetEnabled(bool t_On); + + /** The id of a scope name. The name must stay valid for the whole run (a string literal). */ + static CORE_API uint32 Register(const char* t_Name); + + /** Add one timed call to the calling thread's table. */ + static CORE_API void Record(uint32 t_Id, int64 t_Nanoseconds); + + /** Forget every recorded call (the names stay). */ + static CORE_API void Reset(); + + /** + * A table of every scope, slowest total first: calls, total, average and max in + * milliseconds, and each total as a share of t_WallSeconds when that is above 0. + * Times add up across threads, so a total can pass the wall time. + */ + static CORE_API String Report(double t_WallSeconds); + }; + + /** The timer behind FLING_PROFILE_SCOPE. */ + class ProfileScope + { + public: + explicit ProfileScope(const uint32 t_Id) : m_Id(t_Id), m_On(Profiler::IsEnabled()) + { + if (m_On) + { + m_Start = std::chrono::steady_clock::now(); + } + } + + ~ProfileScope() + { + if (m_On) + { + const auto Elapsed = std::chrono::steady_clock::now() - m_Start; + Profiler::Record(m_Id, std::chrono::duration_cast(Elapsed).count()); + } + } + + ProfileScope(const ProfileScope&) = delete; + ProfileScope& operator=(const ProfileScope&) = delete; + + private: + uint32 m_Id; + bool m_On; + std::chrono::steady_clock::time_point m_Start; + }; +} // namespace Fling + +#ifdef FLING_SHIPPING +#define FLING_PROFILE_SCOPE(Name) ((void)0) +#else +#define FLING_PROFILE_CONCAT_INNER(A, B) A##B +#define FLING_PROFILE_CONCAT(A, B) FLING_PROFILE_CONCAT_INNER(A, B) +/** Time the rest of the enclosing block. Name is a string literal. */ +#define FLING_PROFILE_SCOPE(Name) \ + static const uint32 FLING_PROFILE_CONCAT(FlingProfileId, __LINE__) = ::Fling::Profiler::Register(Name); \ + ::Fling::ProfileScope FLING_PROFILE_CONCAT(FlingProfileScope, \ + __LINE__)(FLING_PROFILE_CONCAT(FlingProfileId, __LINE__)) +#endif diff --git a/FlingEngine/Core/src/LaunchOptions.cpp b/FlingEngine/Core/src/LaunchOptions.cpp index f0517fe1..96248d0c 100644 --- a/FlingEngine/Core/src/LaunchOptions.cpp +++ b/FlingEngine/Core/src/LaunchOptions.cpp @@ -17,6 +17,7 @@ namespace Fling constexpr StringView DumpStateFlag = "dump-state"; constexpr StringView DumpStateTicksFlag = "dump-state-ticks"; constexpr StringView UnattendedFlag = "unattended"; + constexpr StringView ProfileFlag = "profile"; constexpr StringView FramesFlag = "frames"; constexpr StringView FramesPerTickFlag = "frames-per-tick"; constexpr StringView SeedFlag = "seed"; @@ -218,7 +219,8 @@ namespace Fling return false; } - if (!ReadBool(t_CmdLine, UnattendedFlag, t_Out.Unattended, t_OutError)) + if (!ReadBool(t_CmdLine, UnattendedFlag, t_Out.Unattended, t_OutError) || + !ReadBool(t_CmdLine, ProfileFlag, t_Out.Profile, t_OutError)) { return false; } diff --git a/FlingEngine/Core/src/Profiler.cpp b/FlingEngine/Core/src/Profiler.cpp new file mode 100644 index 00000000..f6abebc7 --- /dev/null +++ b/FlingEngine/Core/src/Profiler.cpp @@ -0,0 +1,154 @@ +#include "Profiler.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Fling +{ + namespace + { + /** One scope's numbers on one thread. One writer (the thread), so a load and a store is enough. */ + struct Slot + { + std::atomic TotalNs{0}; + std::atomic MaxNs{0}; + std::atomic Calls{0}; + }; + + struct ThreadTable + { + std::array Slots; + }; + + std::atomic g_Enabled{false}; + std::mutex g_Mutex; + std::vector g_Names; + std::vector> g_Tables; + + ThreadTable& LocalTable() + { + thread_local ThreadTable* Table = nullptr; + if (Table == nullptr) + { + auto Made = std::make_unique(); + Table = Made.get(); + std::lock_guard Lock(g_Mutex); + g_Tables.push_back(std::move(Made)); + } + return *Table; + } + } // namespace + + bool Profiler::IsEnabled() + { + return g_Enabled.load(std::memory_order_relaxed); + } + + void Profiler::SetEnabled(const bool t_On) + { + g_Enabled.store(t_On, std::memory_order_relaxed); + } + + uint32 Profiler::Register(const char* t_Name) + { + std::lock_guard Lock(g_Mutex); + for (uint32 i = 0; i < g_Names.size(); ++i) + { + if (std::strcmp(g_Names[i], t_Name) == 0) + { + return i; + } + } + if (g_Names.size() >= MaxScopes) + { + return MaxScopes - 1; + } + g_Names.push_back(t_Name); + return static_cast(g_Names.size() - 1); + } + + void Profiler::Record(const uint32 t_Id, const int64 t_Nanoseconds) + { + Slot& S = LocalTable().Slots[t_Id]; + S.TotalNs.store(S.TotalNs.load(std::memory_order_relaxed) + t_Nanoseconds, std::memory_order_relaxed); + S.Calls.store(S.Calls.load(std::memory_order_relaxed) + 1, std::memory_order_relaxed); + if (t_Nanoseconds > S.MaxNs.load(std::memory_order_relaxed)) + { + S.MaxNs.store(t_Nanoseconds, std::memory_order_relaxed); + } + } + + void Profiler::Reset() + { + std::lock_guard Lock(g_Mutex); + for (auto& Table : g_Tables) + { + for (Slot& S : Table->Slots) + { + S.TotalNs.store(0, std::memory_order_relaxed); + S.MaxNs.store(0, std::memory_order_relaxed); + S.Calls.store(0, std::memory_order_relaxed); + } + } + } + + String Profiler::Report(const double t_WallSeconds) + { + struct Row + { + const char* Name = nullptr; + int64 TotalNs = 0; + int64 MaxNs = 0; + uint64 Calls = 0; + }; + std::vector Rows; + { + std::lock_guard Lock(g_Mutex); + for (uint32 i = 0; i < g_Names.size(); ++i) + { + Row R; + R.Name = g_Names[i]; + for (const auto& Table : g_Tables) + { + const Slot& S = Table->Slots[i]; + R.TotalNs += S.TotalNs.load(std::memory_order_relaxed); + R.MaxNs = std::max(R.MaxNs, S.MaxNs.load(std::memory_order_relaxed)); + R.Calls += S.Calls.load(std::memory_order_relaxed); + } + if (R.Calls > 0) + { + Rows.push_back(R); + } + } + } + std::sort(Rows.begin(), Rows.end(), [](const Row& A, const Row& B) { return A.TotalNs > B.TotalNs; }); + + String Out = "Profile (ms; times add up across threads)\n"; + char Line[256]; + std::snprintf( + Line, sizeof(Line), "%-40s %10s %10s %10s %10s %7s\n", "scope", "calls", "total", "avg", "max", "wall%"); + Out += Line; + for (const Row& R : Rows) + { + const double TotalMs = static_cast(R.TotalNs) * 1e-6; + const double Share = t_WallSeconds > 0.0 ? TotalMs / (t_WallSeconds * 1000.0) * 100.0 : 0.0; + std::snprintf(Line, + sizeof(Line), + "%-40s %10llu %10.2f %10.4f %10.4f %6.1f%%\n", + R.Name, + static_cast(R.Calls), + TotalMs, + TotalMs / static_cast(R.Calls), + static_cast(R.MaxNs) * 1e-6, + Share); + Out += Line; + } + return Out; + } +} // namespace Fling diff --git a/FlingEngine/Graphics/src/OffscreenSubpass.cpp b/FlingEngine/Graphics/src/OffscreenSubpass.cpp index 6b87fbf1..95ef1f46 100644 --- a/FlingEngine/Graphics/src/OffscreenSubpass.cpp +++ b/FlingEngine/Graphics/src/OffscreenSubpass.cpp @@ -12,6 +12,7 @@ #include "Model.h" #include "OffscreenSubpass.h" #include "PhyscialDevice.h" +#include "Profiler.h" #include "SwapChain.h" #include "UniformBufferObject.h" @@ -101,10 +102,14 @@ namespace Fling assert(OffscreenCmdBuf); // The previous frame is done on the GPU, so the resources of destroyed meshes can go + FLING_PROFILE_SCOPE("Offscreen.Draw"); ReleaseRetiredMeshResources(); // The meshes in this frame's snapshot: new ones get a proxy, gone ones release theirs - SyncProxies(t_Snapshot); + { + FLING_PROFILE_SCOPE("Offscreen.SyncProxies"); + SyncProxies(t_Snapshot); + } // The camera moves on most frames, but it is only one small write OffscreenCameraUBO CameraUBO = {}; @@ -116,15 +121,25 @@ namespace Fling // The view volume of exactly the matrices the shader uses this frame m_CameraViewProjection = CameraUBO.Projection * CameraUBO.View; - CullMeshes(t_Snapshot); + { + FLING_PROFILE_SCOPE("Offscreen.Cull"); + CullMeshes(t_Snapshot); + } - UpdateMeshUniformBuffers(t_Snapshot); - WriteDrawCommands(); + { + FLING_PROFILE_SCOPE("Offscreen.UpdateUbos"); + UpdateMeshUniformBuffers(t_Snapshot); + } + { + FLING_PROFILE_SCOPE("Offscreen.WriteDrawCommands"); + WriteDrawCommands(); + } // The command buffer holds only draw calls and descriptor bindings, not // UBO data. Keep the last recording if the draw list did not change. if (m_RecordedDrawListVersions[t_ActiveSwapImage] != m_DrawListVersion) { + FLING_PROFILE_SCOPE("Offscreen.RecordCommands"); BuildOffscreenCommandBuffer(*OffscreenCmdBuf); m_RecordedDrawListVersions[t_ActiveSwapImage] = m_DrawListVersion; } diff --git a/FlingEngine/Graphics/src/Systems/PublishSnapshotSystem.cpp b/FlingEngine/Graphics/src/Systems/PublishSnapshotSystem.cpp index 9d5f0a7f..00aecc25 100644 --- a/FlingEngine/Graphics/src/Systems/PublishSnapshotSystem.cpp +++ b/FlingEngine/Graphics/src/Systems/PublishSnapshotSystem.cpp @@ -1,5 +1,6 @@ #include "Interpolate.h" #include "Platform.h" +#include "Profiler.h" #include "Systems/PublishSnapshotSystem.h" #include "TransformUtil.h" @@ -56,6 +57,7 @@ namespace Fling void PublishSnapshotSystem::Update(Context& ctx) const { + FLING_PROFILE_SCOPE("Graphics.PublishSnapshot"); RenderSnapshot& snapshot = ctx.Singleton(); const float alpha = ctx.Singleton().BlendAlpha; size_t meshCount = 0; diff --git a/FlingEngine/Graphics/src/VulkanApp.cpp b/FlingEngine/Graphics/src/VulkanApp.cpp index 6ce36e86..403fc202 100644 --- a/FlingEngine/Graphics/src/VulkanApp.cpp +++ b/FlingEngine/Graphics/src/VulkanApp.cpp @@ -18,6 +18,7 @@ #include "LogicalDevice.h" #include "OffscreenSubpass.h" #include "PhyscialDevice.h" +#include "Profiler.h" #include "RenderPipeline.h" #include "RenderSnapshot.h" #include "Screenshot.h" @@ -713,6 +714,7 @@ namespace Fling CmdBuf->SetScissor(0, {scissor}); // Build the command buffers of the render pipelines + FLING_PROFILE_SCOPE("Vk.RecordPipelines"); for (RenderPipeline* Pipeline : m_RenderPipelines) { Pipeline->Draw(*CmdBuf, FrameBuf, ImageIndex, Snapshot, DeltaTime); @@ -805,11 +807,15 @@ namespace Fling m_State->m_InFlightFences[CurrentFrameIndex])); // Finish up the frame by setting the in flight fences to wait ----- - vkWaitForFences(m_LogicalDevice->GetVkDevice(), - 1, - &m_State->m_InFlightFences[CurrentFrameIndex], - VK_TRUE, - std::numeric_limits::max()); + { + // The CPU waits here for the GPU: a long wait means the frame is GPU bound + FLING_PROFILE_SCOPE("Vk.WaitForGpu"); + vkWaitForFences(m_LogicalDevice->GetVkDevice(), + 1, + &m_State->m_InFlightFences[CurrentFrameIndex], + VK_TRUE, + std::numeric_limits::max()); + } // The frame is drawn, and so is a screenshot's copy: the writer thread takes it from here m_Capturer->OnFrameDone(); diff --git a/FlingTests/Core/ProfilerTests.cpp b/FlingTests/Core/ProfilerTests.cpp new file mode 100644 index 00000000..3fc5a6f9 --- /dev/null +++ b/FlingTests/Core/ProfilerTests.cpp @@ -0,0 +1,34 @@ +#include "Profiler.h" + +#include +#include + +using namespace Fling; + +TEST_CASE("Profiler counts scopes only while it is on", "[Profiler]") +{ +#ifndef FLING_SHIPPING + Profiler::SetEnabled(false); + Profiler::Reset(); + { + FLING_PROFILE_SCOPE("ProfilerTest.Off"); + } + REQUIRE(Profiler::Report(0.0).find("ProfilerTest.Off") == String::npos); + + Profiler::SetEnabled(true); + for (int i = 0; i < 3; ++i) + { + FLING_PROFILE_SCOPE("ProfilerTest.On"); + } + std::thread Other([]() { FLING_PROFILE_SCOPE("ProfilerTest.On"); }); + Other.join(); + Profiler::SetEnabled(false); + + // Scopes with one name add up, across threads: 3 calls here and 1 on the other thread + const String Report = Profiler::Report(1.0); + const size_t Row = Report.find("ProfilerTest.On"); + REQUIRE(Row != String::npos); + REQUIRE(Report.find(" 4 ", Row) != String::npos); + Profiler::Reset(); +#endif +} From 86b0c18c393bb5d056e2c925495112c0d63932c9 Mon Sep 17 00:00:00 2001 From: Ben Hoffman Date: Tue, 17 Nov 2026 11:09:38 -0500 Subject: [PATCH 2/2] Compile the profiler out of shipping builds; FLING_PROFILER to override -DFLING_PROFILER=AUTO|ON|OFF (default AUTO: on unless DEFINE_SHIPPING). It sets WITH_PROFILER (0 or 1, PUBLIC on Core). With 0 there is no Profiler class, FLING_PROFILE_SCOPE is nothing, and --profile exits with code 3. ON profiles a shipping build locally; OFF removes it from a dev build. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017NN37Q2jpV81xZaX3ocojK --- AGENTS.md | 3 ++- CMakeLists.txt | 17 +++++++++++++++++ FlingEngine/Application/src/Engine.cpp | 4 ++++ FlingEngine/Core/CMakeLists.txt | 2 ++ FlingEngine/Core/inc/Profiler.h | 11 ++++++++--- FlingEngine/Core/src/LaunchOptions.cpp | 7 +++++++ FlingEngine/Core/src/Profiler.cpp | 4 ++++ FlingTests/Core/ProfilerTests.cpp | 2 +- Skills/building.md | 13 +++++++++++++ 9 files changed, 58 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index bf8c0787..cd45cc3c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -65,7 +65,8 @@ platform setup (Vulkan SDK, GLFW, etc.). - See where the time goes: add `--profile` to any run (it works with `--null-render`, `--offscreen` and a window) and a table of timed scopes prints after the exit line. A scope is `FLING_PROFILE_SCOPE("Name")` from `Profiler.h` (Core): off it costs one - atomic load, and shipping builds remove it. Measure in the build mode you care about: + atomic load. Shipping builds compile it out; `-DFLING_PROFILER=ON|OFF` overrides + that in any build ([`Skills/building.md`](Skills/building.md)). Measure in the build mode you care about: Debug is much slower than RelWithDebInfo for per-entity work. In a window, use `--play` (a window without it starts the editor, which runs no ticks). - Drive a headless run with `--replay-input `. Agents can write their own diff --git a/CMakeLists.txt b/CMakeLists.txt index 13f8f1d2..d56e7a97 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -44,6 +44,22 @@ OPTION( WITH_CRASH_HANDLER_FLAG "Builds CrashHandler: --unattended crash handlin set( FLING_PHYSICS_PROVIDER "Jolt" CACHE STRING "Physics provider to build: Jolt, Bullet, None, or a provider of your own" ) list( APPEND FLING_PHYSICS_PROVIDER_PATHS "${CMAKE_CURRENT_SOURCE_DIR}/FlingEngine" ) +# The instrumented profiler (Profiler.h, --profile). AUTO: in every build except shipping. ON or OFF +# forces it, for example ON to profile a shipping build, or OFF to compile it out of a dev build. +set( FLING_PROFILER "AUTO" CACHE STRING "Profiler: AUTO (on unless DEFINE_SHIPPING), ON or OFF" ) +set_property( CACHE FLING_PROFILER PROPERTY STRINGS AUTO ON OFF ) +if( FLING_PROFILER STREQUAL "AUTO" ) + if( DEFINE_SHIPPING ) + set( FLING_PROFILER_ENABLED OFF ) + else() + set( FLING_PROFILER_ENABLED ON ) + endif() +elseif( FLING_PROFILER ) + set( FLING_PROFILER_ENABLED ON ) +else() + set( FLING_PROFILER_ENABLED OFF ) +endif() + OPTION( ENABLE_MULTICORE "ENABLE_MULTICORE will allow MSVC to use all cores by adding the /MP option" ON) # We can't have the editor without ImGUI! @@ -69,6 +85,7 @@ message( STATUS "WITH_EDITOR_FLAG=${WITH_EDITOR_FLAG}" ) message( STATUS "WITH_IMGUI_FLAG=${WITH_IMGUI_FLAG}" ) message( STATUS "WITH_CRASH_HANDLER_FLAG=${WITH_CRASH_HANDLER_FLAG}" ) message( STATUS "DEFINE_SHIPPING=${DEFINE_SHIPPING}" ) +message( STATUS "FLING_PROFILER=${FLING_PROFILER} (enabled: ${FLING_PROFILER_ENABLED})" ) message( STATUS "ENABLE_MULTICORE=${ENABLE_MULTICORE}" ) message( STATUS "FLING_BUILD_TESTS=${FLING_BUILD_TESTS}" ) message( STATUS "FLING_PHYSICS_PROVIDER=${FLING_PHYSICS_PROVIDER}" ) diff --git a/FlingEngine/Application/src/Engine.cpp b/FlingEngine/Application/src/Engine.cpp index a46c1bd9..26c08229 100644 --- a/FlingEngine/Application/src/Engine.cpp +++ b/FlingEngine/Application/src/Engine.cpp @@ -583,7 +583,9 @@ namespace Fling // sends the messages of a tick over its N frames const float NullRenderDeltaTime = 1.0f / static_cast(m_Settings.SimHz * m_Options.FramesPerTick); +#if WITH_PROFILER Profiler::SetEnabled(m_Options.Profile); +#endif const std::chrono::steady_clock::time_point LoopStart = std::chrono::steady_clock::now(); while (ShouldTick()) { @@ -996,6 +998,7 @@ namespace Fling } PrintExitSummary(t_Code); +#if WITH_PROFILER if (m_Options.Profile) { const double WallSeconds = @@ -1003,6 +1006,7 @@ namespace Fling std::printf("%s", Profiler::Report(WallSeconds).c_str()); std::fflush(stdout); } +#endif // Last, so that every system above can still log while it shuts down Logger::Get().Shutdown(); diff --git a/FlingEngine/Core/CMakeLists.txt b/FlingEngine/Core/CMakeLists.txt index f534a2d6..2dbcb61e 100644 --- a/FlingEngine/Core/CMakeLists.txt +++ b/FlingEngine/Core/CMakeLists.txt @@ -28,6 +28,8 @@ target_compile_definitions(Core PUBLIC # Input recording and playback (--record-input, --replay-input, the editor UI). # Shipping builds do not have it, so a shipped game cannot be driven by an input file. WITH_INPUT_RECORDING=$> + # The instrumented profiler (FLING_PROFILER in the root CMakeLists.txt): off in shipping builds unless asked for + WITH_PROFILER=$ $<$:FLING_SHIPPING> ) diff --git a/FlingEngine/Core/inc/Profiler.h b/FlingEngine/Core/inc/Profiler.h index 3dab872e..384e8e54 100644 --- a/FlingEngine/Core/inc/Profiler.h +++ b/FlingEngine/Core/inc/Profiler.h @@ -6,6 +6,8 @@ #include +#if WITH_PROFILER + namespace Fling { /** @@ -77,9 +79,6 @@ namespace Fling }; } // namespace Fling -#ifdef FLING_SHIPPING -#define FLING_PROFILE_SCOPE(Name) ((void)0) -#else #define FLING_PROFILE_CONCAT_INNER(A, B) A##B #define FLING_PROFILE_CONCAT(A, B) FLING_PROFILE_CONCAT_INNER(A, B) /** Time the rest of the enclosing block. Name is a string literal. */ @@ -87,4 +86,10 @@ namespace Fling static const uint32 FLING_PROFILE_CONCAT(FlingProfileId, __LINE__) = ::Fling::Profiler::Register(Name); \ ::Fling::ProfileScope FLING_PROFILE_CONCAT(FlingProfileScope, \ __LINE__)(FLING_PROFILE_CONCAT(FlingProfileId, __LINE__)) + +#else + +// Compiled out (WITH_PROFILER is 0): a scope is nothing, and there is no Profiler class +#define FLING_PROFILE_SCOPE(Name) ((void)0) + #endif diff --git a/FlingEngine/Core/src/LaunchOptions.cpp b/FlingEngine/Core/src/LaunchOptions.cpp index 96248d0c..90ae8dcc 100644 --- a/FlingEngine/Core/src/LaunchOptions.cpp +++ b/FlingEngine/Core/src/LaunchOptions.cpp @@ -224,6 +224,13 @@ namespace Fling { return false; } +#if !WITH_PROFILER + if (t_Out.Profile) + { + t_OutError = "--profile is not available in this build: configure with -DFLING_PROFILER=ON"; + return false; + } +#endif if (!ReadBool(t_CmdLine, OffscreenFlag, t_Out.Offscreen, t_OutError)) { diff --git a/FlingEngine/Core/src/Profiler.cpp b/FlingEngine/Core/src/Profiler.cpp index f6abebc7..28d06ffd 100644 --- a/FlingEngine/Core/src/Profiler.cpp +++ b/FlingEngine/Core/src/Profiler.cpp @@ -1,5 +1,7 @@ #include "Profiler.h" +#if WITH_PROFILER + #include #include #include @@ -152,3 +154,5 @@ namespace Fling return Out; } } // namespace Fling + +#endif // WITH_PROFILER diff --git a/FlingTests/Core/ProfilerTests.cpp b/FlingTests/Core/ProfilerTests.cpp index 3fc5a6f9..72f8f761 100644 --- a/FlingTests/Core/ProfilerTests.cpp +++ b/FlingTests/Core/ProfilerTests.cpp @@ -7,7 +7,7 @@ using namespace Fling; TEST_CASE("Profiler counts scopes only while it is on", "[Profiler]") { -#ifndef FLING_SHIPPING +#if WITH_PROFILER Profiler::SetEnabled(false); Profiler::Reset(); { diff --git a/Skills/building.md b/Skills/building.md index 34b27c4b..2c68fc01 100644 --- a/Skills/building.md +++ b/Skills/building.md @@ -157,6 +157,19 @@ and `--record-input` / `--replay-input` exit with code 3. A shipped game cannot driven by an input file. Guard code that uses them with `#if WITH_INPUT_RECORDING`. `VirtualInputDeviceInterface` stays, because only code can make one. +## `FLING_PROFILER` + +`-DFLING_PROFILER=AUTO|ON|OFF` (default `AUTO`) decides whether the instrumented +profiler (`Profiler.h`, `--profile`) is built. `AUTO` builds it in every build except +shipping (`DEFINE_SHIPPING=ON`). `ON` builds it anywhere, for example to profile a +shipping build locally; `OFF` compiles it out of a dev build. + +Code reads it as `WITH_PROFILER` (a PUBLIC definition on Core, 0 or 1). When it is 0 +there is no `Profiler` class, `FLING_PROFILE_SCOPE` is nothing, and `--profile` exits +with code 3. Guard any code that calls `Profiler` directly with `#if WITH_PROFILER`; +`FLING_PROFILE_SCOPE` needs no guard. The configure output says what was chosen +(`FLING_PROFILER=AUTO (enabled: ON)`). + ## `FLING_PHYSICS_PROVIDER` Picks the physics provider: `Jolt` (the default), `Bullet`, `None`, or a