### Meson setup command with Tracy options Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Example Meson setup command to enable profiling and set Tracy-specific options like 'on_demand'. ```bash meson setup build --buildtype=debugoptimized -Dtracy_enable=true -Dtracy:on_demand=true ``` -------------------------------- ### CMake Project Setup Source: https://github.com/wolfpld/tracy/blob/master/examples/OpenCLVectorAdd/CMakeLists.txt Configures the minimum required CMake version and names the project. This is a standard starting point for any CMake project. ```cmake cmake_minimum_required(VERSION 3.10) project(OpenCLVectorAdd) ``` -------------------------------- ### Install Tracy Bindings Source: https://github.com/wolfpld/tracy/blob/master/python/CMakeLists.txt Installs the Tracy client and server binding libraries to the runtime and library destinations. ```cmake install(TARGETS TracyClientBindings TracyServerBindings RUNTIME DESTINATION . LIBRARY DESTINATION .) ``` -------------------------------- ### Python Tracy-Client Bindings Example Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Demonstrates the usage of Tracy-Client Python bindings for profiling, including frame marking, zone timing, memory allocation tracking, plot configuration, and message logging. Ensure the tracy_client library is installed. ```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- from time import sleep import numpy as np import tracy_client as tracy @tracy.ScopedFrameDecorator("framed") @tracy.ScopedZoneDecorator(name="work", color=tracy.ColorType.Red4) def work(): sleep(0.05) def main(): assert tracy.program_name("MyApp") assert tracy.app_info("this is a python app") tracy.thread_name("python") # main thread so bit useless plot_id = tracy.plot_config("plot", tracy.PlotFormatType.Number) assert plot_id is not None mem_id = None index = 0 while True: with tracy.ScopedZone(name="test", color=tracy.ColorType.Coral) as zone: index += 1 tracy.frame_mark() inner = tracy.ScopedZone(depth=5, color=tracy.ColorType.Coral) inner.color(index % 5) inner.name(str(index)) inner.enter() if index % 2: tracy.alloc(44, index) else: tracy.free(44) if not index % 2: if mem_id is None: mem_id = tracy.alloc(1337000000, index, name="named", depth=4) assert mem_id is not None else: tracy.alloc(1337000000, index, id=mem_id, depth=4) else: tracy.free(1337000000, mem_id, 4) with tracy.ScopedFrame("custom"): image = np.full([400, 400, 4], index, dtype=np.uint8) assert tracy.frame_image(image.tobytes(), 400, 400) inner.exit() zone.text(index) assert tracy.message(f"we are at index {index}") assert tracy.message(f"we are at index {index}", tracy.ColorType.Coral) assert tracy.plot(plot_id, index) work() sleep(0.1) if __name__ == "__main__": main() ``` -------------------------------- ### Define Executable and Install Source: https://github.com/wolfpld/tracy/blob/master/profiler/helpers/CMakeLists.txt Defines an executable target named 'embed' with specified source files and installs it to the root directory. ```cmake add_executable(embed ../../public/common/tracy_lz4.cpp ../../public/common/tracy_lz4hc.cpp embed.cpp ) install(TARGETS embed DESTINATION .) ``` -------------------------------- ### C++ Main Function Example Source: https://github.com/wolfpld/tracy/blob/master/profiler/src/llm/skill.callstack.md A simple C++ main function demonstrating application lifecycle and potential return stack behavior. ```cpp int main() { auto app = std::make_unique(); app->Run(); app.reset(); } ``` -------------------------------- ### x64 Assembly for Logging Zone Start Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md This x64 assembly code is generated from C++ and logs the start of a profiling zone. It includes buffer management, time retrieval, and source location recording. ```x86asm mov byte ptr [rsp+0C0h],1 ; store zone activity information mov r15d,28h mov rax,qword ptr gs:[58h] ; TLS mov r14,qword ptr [rax] ; queue address mov rdi,qword ptr [r15+r14] ; data address mov rbp,qword ptr [rdi+28h] ; buffer counter mov rbx,rbp and ebx,7Fh ; 128 item buffer jne function+54h -----------+ ; check if current buffer is usable mov rdx,rbp | mov rcx,rdi | call enqueue_begin_alloc | ; reclaim/alloc next buffer shl rbx,5 <-----------------+ ; buffer items are 32 bytes add rbx,qword ptr [rdi+48h] ; calculate queue item address mov byte ptr [rbx],10h ; queue item type rdtsc ; retrieve time shl rdx,20h or rax,rdx ; construct 64 bit timestamp mov qword ptr [rbx+1],rax ; write timestamp lea rax,[__tracy_source_location] ; static struct address mov qword ptr [rbx+9],rax ; write source location data lea rax,[rbp+1] ; increment buffer counter mov qword ptr [rdi+28h],rax ; write buffer counter ``` -------------------------------- ### Instrumenting Fibers with Tracy Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md This example demonstrates how to instrument fibers using Tracy macros. Ensure `TRACY_FIBERS` is defined. Fibers are identified by string names. Zones created within a fiber are attributed to that fiber, even if ended in a different thread. ```cpp const char* fiber = "job1"; TracyCZoneCtx zone; int main() { std::thread t1([]{ TracyFiberEnter(fiber); TracyCZone(ctx, 1); zone = ctx; sleep(1); TracyFiberLeave; }); t1.join(); std::thread t2([]{ TracyFiberEnter(fiber); sleep(1); TracyCZoneEnd(zone); TracyFiberLeave; }); t2.join(); } ``` -------------------------------- ### Start Tracy CUDA Profiling Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Begin profiling all CUDA API calls and GPU activity. This instrumentation is automatic. ```c++ TracyCUDAStartProfiling(ctx); ``` -------------------------------- ### Connection and Lifecycle Queries Source: https://context7.com/wolfpld/tracy/llms.txt Query whether the profiler GUI is currently connected, check if the profiler has started, or set the application name shown in the profiler. ```APIDOC ## TracyIsConnected / TracyIsStarted / TracySetProgramName — Profiler state queries ### Description Query whether the profiler GUI is currently connected, check if the profiler has started, or set the application name shown in the profiler. ### Functions - `TracyIsConnected`: Returns true if the profiler GUI is connected. - `TracyIsStarted`: Returns true if the profiler has started. - `TracySetProgramName(name)`: Sets the application name displayed in the profiler. ``` -------------------------------- ### Run MCP Server Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Installation and execution commands for the Tracy MCP Server. Requires the 'mcp' package and specific environment variables to be set. ```bash pip install mcp python extra/mcp/tracy_mcp.py ``` -------------------------------- ### Run Tracy Capture Daemon Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Use this command to start the capture daemon, specifying the output directory for traces. The daemon listens on UDP port 8086 by default and can be configured with memory limits and filters. ```sh $ tracy-capture-daemon -o ./traces [3 clients] Listening on 0.0.0.0:8086... Press Ctrl+C to stop [1] myapp @ 192.168.1.10:9086 45.2 Mbps | 234 MB | 12.3 s [2] server @ 192.168.1.11:9086 38.7 Mbps | 189 MB | 11.8 s [3] worker @ 192.168.1.12:9086 22.1 Mbps | 145 MB | 10.2 s Total: 106.0 Mbps | 568 MB | Mem: 321 MB ``` -------------------------------- ### Manual Profiler Start and Stop in Fortran Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Manually start and stop the Tracy profiler using `tracy_startup_profiler()` and `tracy_shutdown_profiler()`. Ensure these calls are present in all exit branches. Use `tracy_profiler_started()` to check the status. ```fortran #ifdef TRACY_ENABLE use tracy #endif implicit none #ifdef TRACY_ENABLE if (.not.tracy_profiler_started()) call tracy_startup_profiler() ! wait connection do while (.not.tracy_connected()) call sleep(1) ! GNU extension end do #endif ! do something useful #ifdef TRACY_ENABLE call tracy_shutdown_profiler() #endif ``` -------------------------------- ### Example Call Stack Showing Return Points Source: https://github.com/wolfpld/tracy/blob/master/profiler/src/llm/skill.callstack.md Demonstrates a call stack interpreted as function return points, highlighting optimization where Application::Run returns directly into unique_ptr::reset. ```callstack 0. Application::Run() 1. std::unique_ptr::reset() 2. main() ``` -------------------------------- ### Configure AI Assistant with Tracy MCP Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Configure your AI assistant to connect to the Tracy MCP server using its URL. This example shows a JSON-based MCP configuration. ```json { "mcpServers": { "tracy": { "url": "http://127.0.0.1:47380/sse" } } } ``` -------------------------------- ### Profile CUDA Kernel Execution with Tracy Source: https://context7.com/wolfpld/tracy/llms.txt Initialize Tracy's CUDA context and start profiling. Call `TracyCUDACollect` after kernel launches and `TracyCUDAStopProfiling` on cleanup. Ensure CUDA API calls and kernel launches are automatically instrumented when profiling is active. ```cpp #include "Tracy.hpp" #include "TracyCUDA.hpp" tracy::CUDACtx* cudaTracyCtx = nullptr; void InitCUDAProfiling() { cudaTracyCtx = TracyCUDAContext(); TracyCUDAContextName(cudaTracyCtx, "CUDA:0", 6); TracyCUDAStartProfiling(cudaTracyCtx); } void RunKernels() { MyKernel<<>>(d_data, N); cudaDeviceSynchronize(); TracyCUDACollect(cudaTracyCtx); FrameMark; } void Cleanup() { TracyCUDAStopProfiling(cudaTracyCtx); TracyCUDAContextDestroy(cudaTracyCtx); } ``` -------------------------------- ### C API Zone Start Macros Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Use these macros to mark the beginning of a code zone for profiling. Choose the variant that best suits your needs for naming and coloring. ```c TracyCZone(ctx, active); ``` ```c TracyCZoneN(ctx, name, active); ``` ```c TracyCZoneC(ctx, color, active); ``` ```c TracyCZoneNC(ctx, name, color, active); ``` -------------------------------- ### Manual Control of Tracy Sampling (C Interface) Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Use the C interfaces TracyCBeginSamplingProfiling() and TracyCEndSamplingProfiling() for manual control over sampling start and end times. ```c TracyCBeginSamplingProfiling(); // ... code to profile ... TracyCEndSamplingProfiling(); ``` -------------------------------- ### Initialize Tracy Profiler Module Source: https://github.com/wolfpld/tracy/blob/master/profiler/wasm/index.html Configures the Emscripten Module for Tracy Profiler, including print functions, canvas setup, and status updates. Handles WebGL context loss. ```javascript var statusElement = document.getElementById('status'); var progressElement = document.getElementById('progress'); var spinnerElement = document.getElementById('spinner'); var preloadElement = document.getElementById('preload'); var Module = { preRun: [], postRun: [], print: (function() { return function(text) { if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' '); console.log(text); }; })(), canvas: (function() { var canvas = document.getElementById('canvas'); canvas.addEventListener("webglcontextlost", function(e) { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false); return canvas; })(), setStatus: function(text) { if (!Module.setStatus.last) Module.setStatus.last = { time: Date.now(), text: '' }; if (text === Module.setStatus.last.text) return; var m = text.match(/([^(\]+)\((\d+(\.\d+)?)\/(\d+)\)/); var now = Date.now(); if (m && now - Module.setStatus.last.time < 30) return; Module.setStatus.last.time = now; Module.setStatus.last.text = text; if (m) { text = m[1]; progressElement.value = parseInt(m[2])*100; progressElement.max = parseInt(m[4])*100; progressElement.hidden = false; spinnerElement.hidden = false; preloadElement.hidden = false; } else if (!text) { progressElement.value = null; progressElement.max = null; progressElement.hidden = true; preloadElement.hidden = true; spinnerElement.style.display = 'none'; } statusElement.innerHTML = text; }, totalDependencies: 0, monitorRunDependencies: function(left) { this.totalDependencies = Math.max(this.totalDependencies, left); Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.'); } }; Module.setStatus('Downloading...'); window.onerror = function(event) { Module.setStatus('Exception thrown, see JavaScript console'); spinnerElement.style.display = 'none'; Module.setStatus = function(text) { if (text) console.error('[post-exception status] ' + text); }; }; ``` -------------------------------- ### Named Zone Example Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Use ZoneNamed macros to create zones with custom variable names. This allows for more control over zone management, especially when multiple zones are needed within the same scope. ```cpp { ZoneNamed(Zone1, true); // @⑕@ { ZoneNamed(Zone2, true); // @⑖@ } // @⑗@ } ``` -------------------------------- ### Vulkan Command Buffer Recording Error Example Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Demonstrates an incorrect usage pattern where Tracy GPU zone instrumentation is placed outside the command buffer recording scope. This can lead to errors as the zone destructor may execute after recording has ended. ```c++ { vkBeginCommandBuffer(cmd, &beginInfo); TracyVkZone(ctx, cmd, "Render"); vkEndCommandBuffer(cmd); } ``` -------------------------------- ### Get Frame Boundaries using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Get a list of tuples, where each tuple represents the start and end time (in nanoseconds) of a frame. ```python ctx.get_frame_boundaries() ``` -------------------------------- ### Get First Trace Time using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Retrieve the start time of the trace in nanoseconds using the 'get_first_time' method. ```python ctx.get_first_time() ``` -------------------------------- ### Build and Run Reproduction Case Source: https://github.com/wolfpld/tracy/blob/master/examples/CUDAGraphRepro/README.md Execute these commands to build the project and run the reproduction case that demonstrates the CUDA graph GPU zone issue. ```bash make ./repro ``` -------------------------------- ### Integrate Tracy with CMake FetchContent Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Use CMake FetchContent to download and integrate Tracy. Set necessary options and then make the content available. This avoids manual git submodule management. ```cmake option(TRACY_Fortran "" ON) option(TRACY_DELAYED_INIT "" ON) option(TRACY_MANUAL_LIFETIME "" ON) FetchContent_Declare( tracy GIT_REPOSITORY https://github.com/wolfpld/tracy.git GIT_TAG master GIT_SHALLOW TRUE GIT_PROGRESS TRUE ) FetchContent_MakeAvailable(tracy) ``` -------------------------------- ### Initialize Direct3D 11 Context with Tracy Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Include TracyD3D11.hpp and use TracyD3D11Context to initialize GPU profiling for a Direct3D 11 device and device context. Tracy does not support D3D11 command lists. ```c++ #include "public/tracy/TracyD3D11.hpp" TracyD3D11Ctx ctx = TracyD3D11Context(device, devicecontext); ``` -------------------------------- ### Get GPU Contexts using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Get a list of GPU context summary objects. ```python ctx.get_gpu_contexts() ``` -------------------------------- ### Get Frame Count using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Get the total number of frames for the default frame set. ```python ctx.get_frame_count() ``` -------------------------------- ### Initialize OpenCL Context Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Create an OpenCL context for GPU profiling. The specified device must be part of the context. The context should be destroyed when no longer needed. ```c++ #include "public/tracy/TracyOpenCL.hpp" // ... TracyCLCtx ctx = TracyCLContext(context, device); // ... TracyCLDestroy(ctx); ``` -------------------------------- ### Initialize Vulkan Context with Tracy Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Include TracyVulkan.hpp and use TracyVkContext to initialize GPU profiling for a Vulkan device. Ensure the provided Vulkan objects (physical device, device, queue, command buffer) are compatible and the queue supports graphics or compute operations. ```c++ #include "public/tracy/TracyVulkan.hpp" TracyVkCtx ctx = TracyVkContext(physdev, device, queue, cmdbuf); ``` -------------------------------- ### Get Frame Times using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Get the per-frame durations in nanoseconds for the default frame set. ```python ctx.get_frame_times() ``` -------------------------------- ### Get Timer Resolution using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Get the timer resolution in nanoseconds using the 'get_resolution' method. ```python ctx.get_resolution() ``` -------------------------------- ### Initialize Vulkan Context with Host Calibrated Timestamps Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Use TracyVkContextHostCalibrated for Vulkan 1.2+ with VK_EXT_host_query_reset to reset query pools without a command buffer. Requires calibrated device and host time domains. ```c++ TracyVkCtx ctx = TracyVkContextHostCalibrated(physdev, device, cmdbuf, vkGetPhysicalDeviceCalibrateableTimeDomainsEXT, vkGetCalibratedTimestampsEXT, vkResetQueryPool); ``` -------------------------------- ### Get Named Frame Times using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Get the per-frame durations in nanoseconds for a specific named frame set. ```python ctx.get_frame_times_named(name) ``` -------------------------------- ### Get Symbol Statistics using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Get callstack sample hit counts per symbol. Sort by 'excl' to identify hot functions. ```python ctx.get_symbol_stats() ``` -------------------------------- ### Initialize Direct3D 12 Context Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Create a Direct3D 12 context for GPU profiling. Ensure the device and queue are valid. The context should be destroyed when no longer needed. ```c++ #include "public/tracy/TracyD3D12.hpp" // ... TracyD3D12Ctx ctx = TracyD3D12Context(device, queue); // ... TracyD3D12Destroy(ctx); ``` -------------------------------- ### Get Root Zone Statistics using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Get statistics for only top-level CPU zones per thread. These can be safely summed across zones. ```python ctx.get_root_zone_stats() ``` -------------------------------- ### Tracy C API: Startup and Shutdown Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Functions to manually control the Tracy profiler's startup and shutdown. Ensure TRACY_ENABLE is defined when using these directly. ```c ___tracy_startup_profiler(void); ``` ```c ___tracy_shutdown_profiler(void); ``` -------------------------------- ### Get Zone Durations by Name using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Get a list of individual CPU zone durations in nanoseconds for a given zone name, useful for distribution analysis. ```python ctx.get_zone_durations(name) ``` -------------------------------- ### Initialize Tracy CUDA Context Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Include TracyCUDA.hpp and create a Tracy CUDA context. Only one context is allowed per application. ```c++ #include "public/tracy/TracyCUDA.hpp" tracy::CUDACtx* ctx = TracyCUDAContext(); ``` -------------------------------- ### llama.cpp Mixture of Experts CPU Option Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md The `--n-cpu-moe` option in llama.cpp allows experimentation with CPU offloading for Mixture of Experts models, similar to the `-ngl` GPU offload option. Adjust this to find optimal performance. ```bash --n-cpu-moe ``` -------------------------------- ### Include Configuration Files Source: https://github.com/wolfpld/tracy/blob/master/python/CMakeLists.txt Includes CMake configuration files for general settings, vendor dependencies, and server-specific configurations. ```cmake include(${CMAKE_CURRENT_LIST_DIR}/../cmake/config.cmake) include(${CMAKE_CURRENT_LIST_DIR}/../cmake/vendor.cmake) include(${CMAKE_CURRENT_LIST_DIR}/../cmake/server.cmake) ``` -------------------------------- ### Get All Zone Statistics using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Get statistics for all CPU zones, keyed by zone name. Each ZoneStats object contains min, max, total, avg, count, and sum_sq in nanoseconds. Includes nested zones. ```python ctx.get_all_zone_stats() ``` -------------------------------- ### C++ Function Definitions Source: https://github.com/wolfpld/tracy/blob/master/profiler/src/llm/skill.callstack.md Example C++ functions used to illustrate call stack behavior. ```cpp float Square(float val) { return val*val; } float Distance(Point p1, Point p2) { return sqrt(Square(p1.x-p2.x)+Square(p1.y-p2.y)); } bool CanReach(Player p, Item i) { return Distance(p.pos, i.pos)<5; } ``` -------------------------------- ### Initialize Tracy GPU Context (OpenGL) Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Initializes the Tracy GPU profiling context for OpenGL. This typically involves including the TracyOpenGL.hpp header and calling TracyGpuContext. Only one context per thread is expected. ```c++ #include "public/tracy/TracyOpenGL.hpp" // ... TracyGpuContext; ``` -------------------------------- ### Fiber Management (Fortran) Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Enter and leave fibers for profiling. 'name' must be a null-terminated constant string. ```fortran tracy_fiber_enter(name) ``` ```fortran tracy_fiber_leave() ``` -------------------------------- ### Get Locks using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Retrieve a list of LockSummary objects. Use 'get_lock_wait_stats()' for contention analysis. ```python ctx.get_locks() ``` -------------------------------- ### Registering Custom Profiler Parameters (C++) Source: https://context7.com/wolfpld/tracy/llms.txt Use TracyParameterRegister to set up a callback for runtime parameter changes and TracyParameterSetup to define the parameters exposed to the profiler GUI. This enables interactive experimentation during profiling. ```cpp #include "Tracy.hpp" static int g_SimSteps = 4; void ParameterCallback(void* /*data*/, uint32_t idx, int32_t val) { if (idx == 0) g_SimSteps = val; } void InitProfilingParams() { TracyParameterRegister(ParameterCallback, nullptr); // idx=0, name="SimSteps", isBool=false, initial value=4 TracyParameterSetup(0, "SimSteps", false, g_SimSteps); } ``` -------------------------------- ### List All ctx Methods Source: https://github.com/wolfpld/tracy/blob/master/extra/mcp/eval_guide.md Use this to inspect all available methods on the ctx object. Filter out private methods starting with '_'. ```python print([m for m in dir(ctx) if not m.startswith('_')]) ``` -------------------------------- ### Example Call Stack with Inline Frames Source: https://github.com/wolfpld/tracy/blob/master/profiler/src/llm/skill.callstack.md Illustrates a call stack where functions like Square and Distance are inlined into CanReach. ```callstack 0. Square() [inline 0] 0. Distance() [inline 1] 0. CanReach() [inline 2] 1. ItemsLoop() 2. PlayerLogic() 3. ... ``` -------------------------------- ### OpenGL GPU Zone Profiling with Tracy Source: https://context7.com/wolfpld/tracy/llms.txt Initialize an OpenGL GPU context and wrap GPU work in named zones. GPU timestamps are collected asynchronously each frame via `TracyGpuCollect`. Call `TracyGpuContext` after OpenGL context creation. ```cpp #include "Tracy.hpp" #include "TracyOpenGL.hpp" void InitProfiling() { // Must be called after OpenGL context creation, on the render thread TracyGpuContext; TracyGpuContextName("MainGL", 6); } void RenderFrame() { { TracyGpuZone("Shadow Pass"); RenderShadowMaps(); } { TracyGpuZoneC("Geometry Pass", tracy::Color::Teal); RenderGeometry(); } { // Named zone with variable TracyGpuNamedZone(postZone, "PostProcess", true); RenderPostFX(); } // Collect GPU timestamps — call once per frame after presenting TracyGpuCollect; FrameMark; } ``` -------------------------------- ### Set Minimum CMake Version Source: https://github.com/wolfpld/tracy/blob/master/import/CMakeLists.txt Specifies the minimum version of CMake required for this project. Ensure your CMake installation meets this requirement. ```cmake cmake_minimum_required(VERSION 3.16) ``` -------------------------------- ### Vulkan GPU Zone Profiling with Tracy Source: https://context7.com/wolfpld/tracy/llms.txt Create a Vulkan Tracy context and instrument command buffers with named GPU zones. Timestamps are written into a query pool and read back via `TracyVkCollect`. Call `TracyVkDestroy` to clean up. ```cpp #include "Tracy.hpp" #include "TracyVulkan.hpp" TracyVkCtx vkTracyCtx = nullptr; void InitVulkanProfiling(VkPhysicalDevice physDev, VkDevice device, VkQueue queue, VkCommandBuffer setupCmd) { // Basic context (no calibrated timestamps) vkTracyCtx = TracyVkContext(physDev, device, queue, setupCmd); TracyVkContextName(vkTracyCtx, "MainVkQueue", 11); } void RecordCommandBuffer(VkCommandBuffer cmd) { { TracyVkZone(vkTracyCtx, cmd, "Render Pass"); vkCmdDraw(cmd, 3, 1, 0, 0); } { TracyVkZoneC(vkTracyCtx, cmd, "Compute Dispatch", tracy::Color::Purple); vkCmdDispatch(cmd, 64, 64, 1); } // Collect GPU timestamps (call once after submitting, with a fresh cmd buffer) TracyVkCollect(vkTracyCtx, cmd); } void Cleanup() { TracyVkDestroy(vkTracyCtx); } ``` -------------------------------- ### Get Threads using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Retrieve a list of ThreadData objects, each containing thread ID, count, and fiber status. ```python ctx.get_threads() ``` -------------------------------- ### Get Last Trace Time using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Retrieve the end time of the trace in nanoseconds using the 'get_last_time' method. ```python ctx.get_last_time() ``` -------------------------------- ### Available Tools Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md A list of commands available for interacting with Tracy captures and live applications. ```APIDOC ## Available tools - `list_captures` --- List `*.tracy` files in `TRACY_CAPTURES_DIR` (top-level only). - `list_instances` --- List all captures currently loaded in the server. - `load_capture` --- Load a `.tracy` file by path, optionally giving it an alias. - `connect_instance` --- Set the active instance for subsequent analysis calls. - `live_connect` --- Connect to a running Tracy-instrumented application by address and port. - `discover_instances` --- Scan a port range for running Tracy-instrumented applications. - `eval` --- Execute arbitrary Python against the active `Worker` object (available as `ctx`). Supports `async_mode=True` for long-running queries. - `task` --- Poll, cancel, or list background analysis tasks started with `async_mode=True`. ``` -------------------------------- ### Set Visual Studio Startup Project Source: https://github.com/wolfpld/tracy/blob/master/import/CMakeLists.txt Configures the startup project for Visual Studio IDE. This ensures the main project is launched when debugging. ```cmake set_property(DIRECTORY ${CMAKE_CURRENT_LIST_DIR} PROPERTY VS_STARTUP_PROJECT ${PROJECT_NAME}) ``` -------------------------------- ### Set RPATH for Unix-like Systems Source: https://github.com/wolfpld/tracy/blob/master/python/CMakeLists.txt Configures the runtime search path (RPATH) for shared libraries on Unix-like systems to include the installation directory. ```cmake if (UNIX) set_target_properties(TracyClientBindings PROPERTIES BUILD_RPATH_USE_ORIGIN TRUE INSTALL_RPATH "$ORIGIN/lib") set_target_properties(TracyServerBindings PROPERTIES BUILD_RPATH_USE_ORIGIN TRUE INSTALL_RPATH "$ORIGIN/lib") endif () ``` -------------------------------- ### Get Messages using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Retrieve a list of MessageInfo objects, each containing message time, text, color, and associated thread. ```python ctx.get_messages() ``` -------------------------------- ### Get All GPU Zone Statistics using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Retrieve statistics for all GPU zones. The result is a dictionary keyed by zone name. ```python ctx.get_all_gpu_zone_stats() ``` -------------------------------- ### Instrument Direct3D 12 Command Lists with Tracy Source: https://context7.com/wolfpld/tracy/llms.txt Initialize Tracy's D3D12 context and instrument command lists with zones. Ensure to call `TracyD3D12Collect` and `FrameMark` at the end of command recording. ```cpp #include "Tracy.hpp" #include "TracyD3D12.hpp" TracyD3D12Ctx d3dCtx = nullptr; void InitD3D12Profiling(ID3D12Device* device, ID3D12CommandQueue* queue) { d3dCtx = TracyD3D12Context(device, queue); TracyD3D12ContextName(d3dCtx, "MainD3D12Queue", 14); } void RecordCommands(ID3D12GraphicsCommandList* cmdList) { { TracyD3D12Zone(d3dCtx, cmdList, "Draw Scene"); cmdList->DrawInstanced(36, 1, 0, 0); } { TracyD3D12ZoneC(d3dCtx, cmdList, "Compute", tracy::Color::Magenta); cmdList->Dispatch(8, 8, 1); } TracyD3D12NewFrame(d3dCtx); TracyD3D12Collect(d3dCtx); FrameMark; } void Cleanup() { TracyD3D12Destroy(d3dCtx); } ``` -------------------------------- ### Get Capture Name using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Retrieve the name of the capture stored in the trace using the 'get_capture_name' method of the Worker API. ```python ctx.get_capture_name() ``` -------------------------------- ### Get Callstack Frames using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Resolve a callstack index to a list of frame details, including name, file, line, and address. ```python ctx.get_callstack_frames(callstack_idx) ``` -------------------------------- ### Manual Control of Tracy Sampling (C++) Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Enable manual control over when sampling begins and ends by defining TRACY_SAMPLING_PROFILER_MANUAL_START and using tracy::BeginSamplingProfiling() and tracy::EndSamplingProfiling(). ```c++ #define TRACY_SAMPLING_PROFILER_MANUAL_START tracy::BeginSamplingProfiling(); // ... code to profile ... tracy::EndSamplingProfiling(); ``` -------------------------------- ### Query Tracy Profiler State and Set Application Name Source: https://context7.com/wolfpld/tracy/llms.txt Use `TracyIsConnected` to check if the profiler GUI is connected, `TracyIsStarted` to check if profiling has begun, and `TracySetProgramName` to set the application name displayed in the profiler. ```cpp #include "Tracy.hpp" void OnStartup() { TracySetProgramName("MyGame Release 1.0"); if (TracyIsConnected) { TracyMessageL("Profiler connected at startup"); } } void ExpensiveDebugDump() { // Only perform costly data collection when profiler is actually watching if (!TracyIsConnected) return; for (auto& obj : objects) { char buf[256]; int len = obj.DebugString(buf, sizeof(buf)); TracyMessage(buf, (size_t)len); } } ``` -------------------------------- ### Get Zone Statistics by Source Location using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Retrieve statistics for a specific CPU zone identified by its source location ID. ```python ctx.get_zone_stats(srcloc_id) ``` -------------------------------- ### Import Fuchsia Tracing Data Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Use `tracy-import-fuchsia` to convert Fuchsia's tracing format to Tracy's format. The output file can then be loaded by `tracy-profiler`. ```sh $ tracy-import-fuchsia mytracefile.fxt mytracefile.tracy $ tracy-profiler mytracefile.tracy ``` -------------------------------- ### Get Capture Program String using Worker API Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Retrieve the program string associated with the capture using the 'get_capture_program' method of the Worker API. ```python ctx.get_capture_program() ``` -------------------------------- ### C API Get Time Function Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Retrieve the current profiler time using this function. It is equivalent to calling Profiler::GetTime() from C++ code. ```c ___tracy_get_time() ``` -------------------------------- ### Docker Configuration for CPU Sampling Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md This sample configuration grants elevated access rights to a Docker container to enable CPU sampling features. Tested on Ubuntu 22.04.3 with Docker 24.0.4. ```bash --privileged --mount "type=bind,source=/sys/kernel/debug,target=/sys/kernel/debug,readonly" --user 0:0 --pid=host ``` -------------------------------- ### Link Tracy Client with FetchContent in CMake Source: https://github.com/wolfpld/tracy/blob/master/manual/tracy.md Link the Tracy client library when using FetchContent. For LTO, also link the base TracyClient. ```cmake target_link_libraries( PUBLIC TracyClientF90) ``` ```cmake target_link_libraries( PUBLIC TracyClient TracyClientF90) ```