% !TeX spellcheck = en_US
\documentclass[hidelinks,titlepage,a4paper]{article}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{newpxtext,newpxmath}
\linespread{1.05} % Line spacing - Palatino needs more space between lines
\usepackage{microtype}
\usepackage[group-separator={,}]{siunitx}
\usepackage[tikz]{bclogo}
\usepackage{pgfplots}
\usepackage{appendix}
\usepackage{verbatim}
\usepackage[hyphens]{url}
\usepackage{hyperref} % For hyperlinks in the PDF
\usepackage{fontawesome5}
\usepackage[os=win]{menukeys}
\usepackage{xfrac}
\usepackage[euler]{textgreek}
\usepackage{nameref}

\usepackage[hmarginratio=1:1,top=32mm,columnsep=20pt]{geometry} % Document margins
\geometry{a4paper,textwidth=6.5in,hmarginratio=1:1,
  textheight=9in,vmarginratio=1:1,heightrounded}

\usepackage{titlesec}
\setcounter{secnumdepth}{4}
\setcounter{tocdepth}{4}

\titleformat{\paragraph}
{\normalfont\normalsize\bfseries}{\theparagraph}{1em}{}
\titlespacing*{\paragraph}
{0pt}{3.25ex plus 1ex minus .2ex}{1.5ex plus .2ex}

\usepackage{fancyhdr} % Headers and footers
\pagestyle{fancy} % All pages have headers and footers
\fancyhead{} % Blank out the default header
\fancyfoot{} % Blank out the default footer
\fancyhead[L]{Tracy Profiler}
\fancyhead[R]{The user manual}
\fancyfoot[RO]{\thepage} % Custom footer text

\usepackage{listings}
\usepackage{xcolor}
\usepackage{float}
\lstset{language=C++}
\lstset{
         basicstyle=\footnotesize\ttfamily,
         tabsize=4,
         extendedchars=true,
         breaklines=true,
         stringstyle=\ttfamily,
         showspaces=false,
         xleftmargin=17pt,
         framexleftmargin=17pt,
         framexrightmargin=5pt,
         framexbottommargin=4pt,
         showstringspaces=false,
         escapeinside={@}{@},
         aboveskip=\baselineskip,
         belowskip=\baselineskip
}

\usepackage[hang,small,labelfont=bf,up,textfont=it,up]{caption} % Custom captions under/above floats in tables or figures

\usepackage{tikz}
\usetikzlibrary{arrows.meta,positioning,shapes,patterns}

\newcommand{\LMB}{\includegraphics[height=.8\baselineskip]{icons/lmb}}
\newcommand{\RMB}{\includegraphics[height=.8\baselineskip]{icons/rmb}}
\newcommand{\MMB}{\includegraphics[height=.8\baselineskip]{icons/mmb}}
\newcommand{\Scroll}{\includegraphics[height=.8\baselineskip]{icons/scroll}}

\newcommand*\circled[1]{\tikz[baseline=(char.base)]{
    \node[shape=circle,draw,inner sep=1.5pt] (char) {#1};}}

\begin{document}

\begin{titlepage}
\centering
{\fontsize{120}{140}\selectfont Tracy Profiler}

\vspace{50pt} {\Huge\fontfamily{lmtt}\selectfont The user manual}

\vfill \includegraphics[height=40mm]{../icon/icon}

\vfill
\large\textbf{Bartosz Taudul} \href{mailto:wolf@nereid.pl}{<wolf@nereid.pl>}

\vspace{10pt}
\today
\vfill
\url{https://github.com/wolfpld/tracy}
\end{titlepage}

\section*{Quick overview}

Hello and welcome to the Tracy Profiler user manual! Here you will find all the information you need to start using the profiler. This manual has the following layout:

\begin{itemize}
\item Chapter~\ref{quicklook}, \emph{\nameref{quicklook}}, gives a short description of what Tracy is and how it works.
\item Chapter~\ref{firststeps}, \emph{\nameref{firststeps}}, shows how you can integrate the profiler into your application and how to build the graphical user interface (section~\ref{buildingserver}). At this point, you will be able to establish a connection from the profiler to your application.
\item Chapter~\ref{client}, \emph{\nameref{client}}, provides information on how to instrument your application, in order to retrieve useful profiling data. This includes a description of the C API (section~\ref{capi}), which enables usage of Tracy in any programming language.
\item Chapter~\ref{capturing}, \emph{\nameref{capturing}}, goes into more detail on how the profiling information can be captured and stored on disk.
\item Chapter~\ref{analyzingdata}, \emph{\nameref{analyzingdata}}, guides you through the graphical user interface of the profiler.
\item Chapter~\ref{csvexport}, \emph{\nameref{csvexport}}, explains how to export some zone timing statistics into a CSV format.
\item Chapter~\ref{importingdata}, \emph{\nameref{importingdata}}, documents how to import data from other profilers.
\item Chapter~\ref{configurationfiles}, \emph{\nameref{configurationfiles}}, gives information on the profiler settings.
\end{itemize}

\section*{Quick-start guide}

For Tracy to profile your application, you will need to integrate the profiler into your application and run an independent executable that will act both as a server with which your application will communicate and as a profiling viewer. The most basic integration looks like this:

\begin{itemize}
\item Add the Tracy repository to your project directory.
\item Tracy source files in the \texttt{project/tracy/public} directory.
\item Add \texttt{TracyClient.cpp} as a source file.
\item Add \texttt{tracy/Tracy.hpp} as an include file.
\item Include \texttt{Tracy.hpp} in every file you are interested in profiling.
\item Define \texttt{TRACY\_ENABLE} for the \textbf{WHOLE} project.
\item Add the macro \texttt{FrameMark} at the end of each frame loop.
\item Add the macro \texttt{ZoneScoped} as the first line of your function definitions to include them in the profile.
\item Compile and run both your application and the profiler server.
\item Hit \emph{Connect} on the profiler server.
\item Tada! You're profiling your program!
\end{itemize}

There's much more Tracy can do, which can be explored by carefully reading this manual. In case any problems should surface, refer to section~\ref{initialsetup} to ensure you've correctly included Tracy in your project. Additionally, you should refer to section~\ref{client} to make sure you are using \texttt{FrameMark}, \texttt{ZoneScoped}, and any other Tracy constructs correctly.

\newpage

\tableofcontents

\newpage

\section{A quick look at Tracy Profiler}
\label{quicklook}

Tracy is a real-time, nanosecond resolution \emph{hybrid frame and sampling profiler} that can you can use for remote or embedded telemetry of games and other applications. It can profile CPU\footnote{Direct support is provided for C, C++, and Lua integration. At the same time, third-party bindings to many other languages exist on the internet, such as Rust, Zig, C\#, OCaml, Odin, etc.}, GPU\footnote{All major graphic APIs: OpenGL, Vulkan, Direct3D 11/12, OpenCL.}, memory allocations, locks, context switches, automatically attribute screenshots to captured frames, and much more.

While Tracy can perform statistical analysis of sampled call stack data, just like other \emph{statistical profilers} (such as VTune, perf, or Very Sleepy), it mainly focuses on manual markup of the source code. Such markup allows frame-by-frame inspection of the program execution. For example, you will be able to see exactly which functions are called, how much time they require, and how they interact with each other in a multi-threaded environment. In contrast, the statistical analysis may show you the hot spots in your code, but it cannot accurately pinpoint the underlying cause for semi-random frame stutter that may occur every couple of seconds.

Even though Tracy targets \emph{frame} profiling, with the emphasis on analysis of \emph{frame time} in real-time applications (i.e.~games), it does work with utilities that do not employ the concept of a frame. There's nothing that would prohibit the profiling of, for example, a compression tool or an event-driven UI application.

You may think of Tracy as the RAD Telemetry plus Intel VTune, on overdrive.

\subsection{Real-time}

The concept of Tracy being a real-time profiler may be explained in a couple of different ways:

\begin{enumerate}
\item The profiled application is not slowed down by profiling\footnote{See section~\ref{perfimpact} for a benchmark.}. The act of recording a profiling event has virtually zero cost -- it only takes a few nanoseconds. Even on low-power mobile devices, execution speed has no noticeable impact.
\item The profiler itself works in real-time, without the need to process collected data in a complex way. Actually, it is pretty inefficient in how it works because it recalculates the data it presents each frame anew. And yet, it can run at 60 frames per second.
\item The profiler has full functionality when the profiled application runs and the data is still collected. You may interact with your application and immediately switch to the profiler when a performance drop occurs.
\end{enumerate}

\subsection{Nanosecond resolution}

It is hard to imagine how long a nanosecond is. One good analogy is to compare it with a measure of length. Let's say that one second is one meter (the average doorknob is at the height of one meter).

One millisecond ($\frac{1}{1000}$ of a second) would be then the length of a millimeter. The average size of a red ant or the width of a pencil is 5 or 6~\si{\milli\metre}. A modern game running at 60 frames per second has only 16~\si{\milli\second} to update the game world and render the entire scene.

One microsecond ($\frac{1}{1000}$ of a millisecond) in our comparison equals one micron. The diameter of a typical bacterium ranges from 1 to 10 microns. The diameter of a red blood cell or width of a strand of spider web silk is about 7~\si{\micro\metre}.

And finally, one nanosecond ($\frac{1}{1000}$ of a microsecond) would be one nanometer. The modern microprocessor transistor gate, the width of the DNA helix, or the thickness of a cell membrane are in the range of 5~\si{\nano\metre}. In one~\si{\nano\second} the light can travel only 30~\si{\centi\meter}.

Tracy can achieve single-digit nanosecond measurement resolution due to usage of hardware timing mechanisms on the x86 and ARM architectures\footnote{In both 32 and 64~bit variants. On x86, Tracy requires a modern version of the \texttt{rdtsc} instruction (Sandy Bridge and later). Note that Time Stamp Counter readings' resolution may depend on the used hardware and its design decisions related to how TSC synchronization is handled between different CPU sockets, etc. On ARM-based systems Tracy will try to use the timer register (\textasciitilde 40 \si{\nano\second} resolution). If it fails (due to kernel configuration), Tracy falls back to system provided timer, which can range in resolution from 250 \si{\nano\second} to 1 \si{\micro\second}.}. Other profilers may rely on the timers provided by the operating system, which do have significantly reduced resolution (about 300~\si{\nano\second} -- 1~\si{\micro\second}). This is enough to hide the subtle impact of cache access optimization, etc.

\subsubsection{Timer accuracy}

You may wonder why it is vital to have a genuinely high resolution timer\footnote{Interestingly the \texttt{std::chrono::high\_resolution\_clock} is not really a high-resolution clock.}. After all, you only want to profile functions with long execution times and not some short-lived procedures that have no impact on the application's run time.

It is wrong to think so. Optimizing a function to execute in 430~\si{\nano\second}, instead of 535~\si{\nano\second} (note that there is only a 100~\si{\nano\second} difference) results in 14 \si{\milli\second} savings if the function is executed 18000 times\footnote{This is a real optimization case. The values are median function run times and do not reflect the real execution time, which explains the discrepancy in the total reported time.}. It may not seem like a big number, but this is how much time there is to render a complete frame in a 60~FPS game. Imagine that this is your particle processing loop.

You also need to understand how timer precision is reflected in measurement errors. Take a look at figure~\ref{timer}. There you can see three discrete timer tick events, which increase the value reported by the timer by 300~\si{\nano\second}. You can also see four readings of time ranges, marked $A_1$, $A_2$; $B_1$, $B_2$; $C_1$, $C_2$ and $D_1$, $D_2$.

\begin{figure}[h]
\centering\begin{tikzpicture}
\draw [-{Stealth}] (-1.5, 0) -- (11.5, 0) node[anchor=south east] {Time};
\draw (0, -0.25) -- (0, 0.25) node[anchor=south] {\faClock};
\draw (5, -0.25) -- (5, 0.25) node[anchor=south] {\faClock};
\draw (10, -0.25) -- (10, 0.25) node[anchor=south] {\faClock};
\draw (0, 0.9) -- (0, 1) -- (5, 1) -- (5, 0.9);
\draw (2.5, 1) node[anchor=south] {300~\si{\nano\second}};

\draw (4.9, 0.1) -- (4.9, -0.1);
\draw [{Stealth}-] (4.9, -0.2) -- (4.8, -0.7) node[anchor=north] {$A_1$};
\draw (5.1, 0.1) -- (5.1, -0.1);
\draw [{Stealth}-] (5.1, -0.2) -- (5.2, -0.7) node[anchor=north] {$A_2$};

\draw (0.1, 0.1) -- (0.1, -0.1);
\draw [{Stealth}-] (0.1, -0.2) -- (0.2, -0.7) node[anchor=north] {$B_1$};
\draw (9.9, 0.1) -- (9.9, -0.1);
\draw [{Stealth}-] (9.9, -0.2) -- (9.8, -0.7) node[anchor=north] {$B_2$};

\draw (-0.1, 0.1) -- (-0.1, -0.1);
\draw [{Stealth}-] (-0.1, -0.2) -- (-0.2, -0.7) node[anchor=north] {$C_1$};
\draw (10.1, 0.1) -- (10.1, -0.1);
\draw [{Stealth}-] (10.1, -0.2) -- (10.2, -0.7) node[anchor=north] {$C_2$};

\draw (2.4, 0.1) -- (2.4, -0.1);
\draw [{Stealth}-] (2.4, -0.2) -- (2.3, -0.7) node[anchor=north] {$D_1$};
\draw (2.6, 0.1) -- (2.6, -0.1);
\draw [{Stealth}-] (2.6, -0.2) -- (2.7, -0.7) node[anchor=north] {$D_2$};
\end{tikzpicture}
\caption{Low precision (300~ns) timer. Discrete timer ticks are indicated by the \faClock{} icon.}
\label{timer}
\end{figure}

Now let's take a look at the timer readings.

\begin{itemize}
\item The $A$ and $D$ ranges both take a very short amount of time (10~\si{\nano\second}), but the $A$ range is reported as 300~\si{\nano\second}, and the $D$ range is reported as 0~\si{\nano\second}.
\item The $B$ range takes a considerable amount of time (590~\si{\nano\second}), but according to the timer readings, it took the same time (300~\si{\nano\second}) as the short lived $A$ range.
\item The $C$ range (610~\si{\nano\second}) is only 20~\si{\nano\second} longer than the $B$ range, but it is reported as 900~\si{\nano\second}, a 600~\si{\nano\second} difference!
\end{itemize}

Here, you can see why using a high-precision timer is essential. While there is no escape from the measurement errors, a profiler can reduce their impact by increasing the timer accuracy.

\subsection{Frame profiler}

Tracy aims to give you an understanding of the inner workings of a tight loop of a game (or any other kind of interactive application). That's why it slices the execution time of a program using the \emph{frame}\footnote{A frame is used to describe a single image displayed on the screen by the game (or any other program), preferably 60 times per second to achieve smooth animation. You can also think about physics update frames, audio processing frames, etc.} as a basic work-unit\footnote{Frame usage is not required. See section~\ref{markingframes} for more information.}. The most interesting frames are the ones that took longer than the allocated time, producing visible hitches in the on-screen animation. Tracy allows inspection of such misbehavior.

\subsection{Sampling profiler}

Tracy can periodically sample what the profiled application is doing, which provides detailed performance information at the source line/assembly instruction level. This can give you a deep understanding of how the processor executes the program. Using this information, you can get a coarse view at the call stacks, fine-tune your algorithms, or even 'steal' an optimization performed by one compiler and make it available for the others.

On some platforms, it is possible to sample the hardware performance counters, which will give you information not only \emph{where} your program is running slowly, but also \emph{why}.

\subsection{Remote or embedded telemetry}

Tracy uses the client-server model to enable a wide range of use-cases (see figure~\ref{clientserver}). For example, you may profile a game on a mobile phone over the wireless connection, with the profiler running on a desktop computer. Or you can run the client and server on the same machine, using a localhost connection. It is also possible to embed the visualization front-end in the profiled application, making the profiling self-contained\footnote{See section~\ref{embeddingserver} for guidelines.}.

\begin{figure}[h]
\centering\begin{tikzpicture}
[inner sep=1.5mm, bend angle=30,
 thread/.style={rectangle, draw},
 module/.style={rectangle, draw, rounded corners=8pt},
 collect/.style={{Stealth}-, shorten <=4pt, shorten >=4pt},
 network/.style={cloud, draw, cloud ignores aspect, cloud puffs=11.6}]

\node[thread] (t1) {\faRandom{} Thread 1};
\node[thread] (t2) [below=of t1] {\faRandom{} Thread 2};
\node[thread] (t3) [below=of t2] {\faRandom{} Thread 3};

\node[module] (client) [right=of t2] {Tracy client}
	edge [collect, bend right] (t1)
	edge [collect] (t2)
	edge [collect, bend left] (t3);

\node[network] (network) [right=of client] {Network}
	edge [collect] (client);

\node[module] (server) [right=of network] {Tracy server}
	edge [collect] (network);

\begin{scope}[node distance=12pt, bend angle=25]
\node[thread] (display) [above right=of server] {\faTv{} Display}
	edge [collect, bend right] (server);
\node[thread] (storage) [below right=of server] {\faDatabase{} Storage}
	edge [collect, bend left] (server);
\end{scope}
\end{tikzpicture}
\caption{Client-server model.}
\label{clientserver}
\end{figure}

In Tracy terminology, the profiled application is a \emph{client}, and the profiler itself is a \emph{server}. It was named this way because the client is a thin layer that just collects events and sends them for processing and long-term storage on the server. The fact that the server needs to connect to the client to begin the profiling session may be a bit confusing at first.

\subsection{Why Tracy?}

You may wonder why you should use Tracy when so many other profilers are available. Here are some arguments:

\begin{itemize}
\item Tracy is free and open-source (BSD license), while RAD Telemetry costs about \$8000 per year.
\item Tracy provides out-of-the-box Lua bindings. It has been successfully integrated with other native and interpreted languages (Rust, Arma scripting language) using the C API (see chapter~\ref{capi} for reference).
\item Tracy has a wide variety of profiling options. For example, you can profile CPU, GPU, locks, memory allocations, context switches, and more.
\item Tracy is feature-rich. For example, statistical information about zones, trace comparisons, or inclusion of inline function frames in call stacks (even in statistics of sampled stacks) are features unique to Tracy.
\item Tracy focuses on performance. It uses many tricks to reduce memory requirements and network bandwidth. As a result, the impact on the client execution speed is minimal, while other profilers perform heavy data processing within the profiled application (and then claim to be lightweight).
\item Tracy uses low-level kernel APIs, or even raw assembly, where other profilers rely on layers of abstraction.
\item Tracy is multi-platform right from the very beginning. Both on the client and server-side. Other profilers tend to have Windows-specific graphical interfaces.
\item Tracy can handle millions of frames, zones, memory events, and so on, while other profilers tend to target very short captures.
\item Tracy doesn't require manual markup of interesting areas in your code to start profiling. Instead, you may rely on automated call stack sampling and add instrumentation later when you know where it's needed.
\item Tracy provides a mapping of source code to the assembly, with detailed information about the cost of executing each instruction on the CPU.
\end{itemize}

\subsection{Performance impact}
\label{perfimpact}

Let's profile an example application to check how much slowdown is introduced by using Tracy. For this purpose we have used etcpak\footnote{\url{https://github.com/wolfpld/etcpak}}. The input data was a $16384 \times 16384$ pixels test image, and the $4 \times 4$ pixel block compression function was selected to be instrumented. The image was compressed on 12 parallel threads, and the timing data represents a mean compression time of a single image.

The results are presented in table~\ref{PerformanceImpact}. Dividing the average of run time differences (37.7 \si{\milli\second}) by the count of captured zones per single image (\num{16777216}) shows us that the impact of profiling is only 2.25 \si{\nano\second} per zone (this includes two events: start and end of a zone).

\begin{table}[h]
\centering
\begin{tabular}[h]{c|c|c|c|c|c}
\textbf{Mode} & \textbf{Zones (total)} & \textbf{Zones (single image)} & \textbf{Clean run} & \textbf{Profiling run} & \textbf{Difference} \\ \hline
ETC1 & \num{201326592} & \num{16777216} & 110.9 \si{\milli\second} & 148.2 \si{\milli\second} & +37.3 \si{\milli\second} \\
ETC2 & \num{201326592} & \num{16777216} & 212.4 \si{\milli\second} & 250.5 \si{\milli\second} & +38.1 \si{\milli\second}
\end{tabular}
\caption{Zone capture time cost.}
\label{PerformanceImpact}
\end{table}

\subsubsection{Assembly analysis}

To see how Tracy achieves such small overhead (only 2.25 \si{\nano\second}), let's take a look at the assembly. The following x64 code is responsible for logging the start of a zone. Do note that it is generated by compiling fully portable C++.

\begin{lstlisting}[language={[x86masm]Assembler}]
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
\end{lstlisting}

The second code block, responsible for ending a zone, is similar but smaller, as it can reuse some variables retrieved in the above code.

\subsection{Examples}

To see how to integrate Tracy into your application, you may look at example programs in the \texttt{examples} directory. Looking at the commit history might be the best way to do that.

\subsection{On the web}

Tracy can be found at the following web addresses:

\begin{itemize}
\item Homepage -- \url{https://github.com/wolfpld/tracy}
\item Bug tracker -- \url{https://github.com/wolfpld/tracy/issues}
\item Discord chat -- \url{https://discord.gg/pk78auc}
\item Sponsoring development -- \url{https://github.com/sponsors/wolfpld/}
\item Interactive demo -- \url{https://tracy.nereid.pl/}
\end{itemize}

\subsubsection{Binary distribution}

The version releases of the profiler are provided as precompiled Windows binaries for download at \url{https://github.com/wolfpld/tracy/releases}, along with the user manual. You will need to install the latest Visual C++ redistributable package to use them.

Development builds of Windows binaries, and the user manual are available as artifacts created by the automated Continuous Integration system on GitHub.

Note that these binary releases require AVX2 instruction set support on the processor. If you have an older CPU, you will need to set a proper instruction set architecture in the project properties and build the executables yourself.

\section{First steps}
\label{firststeps}

Tracy Profiler supports  MSVC, GCC, and clang. You will need to use a reasonably recent version of the compiler due to the C++11 requirement. The following platforms are confirmed to be working (this is not a complete list):

\begin{itemize}
\item Windows (x86, x64)
\item Linux (x86, x64, ARM, ARM64)
\item Android (ARM, ARM64, x86)
\item FreeBSD (x64)
\item WSL (x64)
\item OSX (x64)
\item iOS (ARM, ARM64)
\end{itemize}

Moreover, the following platforms are not supported due to how secretive their owners are but were reported to be working after extending the system integration layer:

\begin{itemize}
\item PlayStation 4
\item Xbox One
\item Nintendo Switch
\item Google Stadia
\end{itemize}

You may also try your luck with Mingw, but don't get your hopes too high. This platform was usable some time ago, but nobody is actively working on resolving any issues you might encounter with it.

\subsection{Initial client setup}
\label{initialsetup}

The recommended way to integrate Tracy into an application is to create a git submodule in the repository (assuming that you use git for version control). This way, it is straightforward to update Tracy to newly released versions. If that's not an option, all the files required to integrate your application with Tracy are contained in the \texttt{public} directory.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bclampe
]{What revision should I use?}
You have two options when deciding on the Tracy Profiler version you want to use. Take into consideration the following pros and cons:

\begin{itemize}
\item Using the last-version-tagged revision will give you a stable platform to work with. You won't experience any breakages, major UI overhauls, or network protocol changes. Unfortunately, you also won't be getting any bug fixes.
\item Working with the bleeding edge \texttt{master} development branch will give you access to all the new improvements and features added to the profiler. While it is generally expected that \texttt{master} should always be usable, \textbf{there are no guarantees that it will be so.}
\end{itemize}

Do note that all bug fixes and pull requests are made against the \texttt{master} branch.
\end{bclogo}

With the source code included in your project, add the \texttt{public/TracyClient.cpp} source file to the IDE project or makefile. You're done. Tracy is now integrated into the application.

In the default configuration, Tracy is disabled. This way, you don't have to worry that the production builds will collect profiling data. To enable profiling, you will probably want to create a separate build configuration, with the \texttt{TRACY\_ENABLE} define.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Important}
\begin{itemize}
\item Double-check that the define name is entered correctly (as \texttt{TRACY\_ENABLE}), don't make a mistake of adding an additional \texttt{D} at the end. Make sure that this macro is defined for all files across your project (e.g. it should be specified in the \texttt{CFLAGS} variable, which is always passed to the compiler, or in an equivalent way), and \emph{not} as a \texttt{\#define} in just some of the source files.
\item Tracy does not consider the value of the definition, only the fact if the macro is defined or not (unless specified otherwise). Be careful not to make the mistake of assigning numeric values to Tracy defines, which could lead you to be puzzled why constructs such as \texttt{TRACY\_ENABLE=0} don't work as you expect them to do.
\end{itemize}
\end{bclogo}

You should compile the application you want to profile with all the usual optimization options enabled (i.e.~make a release build). Profiling debugging builds makes little sense, as the unoptimized code and additional checks (asserts, etc.) completely change how the program behaves. In addition, you should enable usage of the native architecture of your CPU (e.g.~\texttt{-march=native}) to leverage the expanded instruction sets, which may not be available in the default baseline target configuration.

Finally, on Unix, make sure that the application is linked with libraries \texttt{libpthread} and \texttt{libdl}. BSD systems will also need to be linked with \texttt{libexecinfo}.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bclampe
]{CMake integration}
You can integrate Tracy with CMake by adding the git submodule folder as a subdirectory.

\begin{lstlisting}
# set options before add_subdirectory
# available options: TRACY_ENABLE, TRACY_ON_DEMAND, TRACY_NO_BROADCAST, TRACY_NO_CODE_TRANSFER, ...
option(TRACY_ENABLE "" ON)
option(TRACY_ON_DEMAND "" ON)
add_subdirectory(3rdparty/tracy)  # target: TracyClient or alias Tracy::TracyClient
\end{lstlisting}

Link \texttt{Tracy::TracyClient} to any target where you use Tracy for profiling:

\begin{lstlisting}
target_link_libraries(<TARGET> PUBLIC Tracy::TracyClient)
\end{lstlisting}
\end{bclogo}

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bclampe
]{CMake FetchContent}
When using CMake 3.11 or newer, you can use Tracy via CMake FetchContent. In this case, you do not need to add a git submodule for Tracy manually. Add this to your CMakeLists.txt:

\begin{lstlisting}
FetchContent_Declare(
    tracy
    GIT_REPOSITORY https://github.com/wolfpld/tracy.git
    GIT_TAG        master
    GIT_SHALLOW    TRUE
    GIT_PROGRESS   TRUE
)

FetchContent_MakeAvailable(tracy)
\end{lstlisting}

Then add this to any target where you use tracy for profiling:

\begin{lstlisting}
target_link_libraries(<TARGET> PUBLIC TracyClient)
\end{lstlisting}
\end{bclogo}

\subsubsection{Short-lived applications}

In case you want to profile a short-lived program (for example, a compression utility that finishes its work in one second), set the \texttt{TRACY\_NO\_EXIT} environment variable to $1$. With this option enabled, Tracy will not exit until an incoming connection is made, even if the application has already finished executing. If your platform doesn't support an easy setup of environment variables, you may also add the \texttt{TRACY\_NO\_EXIT} define to your build configuration, which has the same effect.

\subsubsection{On-demand profiling}
\label{ondemand}

By default, Tracy will begin profiling even before the program enters the \texttt{main} function. However, suppose you don't want to perform a full capture of the application lifetime. In that case, you may define the \texttt{TRACY\_ON\_DEMAND} macro, which will enable profiling only when there's an established connection with the server.

You should note that if on-demand profiling is \emph{disabled} (which is the default), then the recorded events will be stored in the system memory until a server connection is made and the data can be uploaded\footnote{This memory is never released, but the profiler reuses it for collection of other events.}. Depending on the amount of the things profiled, the requirements for event storage can quickly grow up to a couple of gigabytes. Furthermore, since this data is no longer available after the initial connection, you won't be able to perform a second connection to a client unless the on-demand mode is used.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcattention
]{Caveats}
The client with on-demand profiling enabled needs to perform additional bookkeeping to present a coherent application state to the profiler. This incurs additional time costs for each profiling event.
\end{bclogo}

\subsubsection{Client discovery}

By default, the Tracy client will announce its presence to the local network\footnote{Additional configuration may be required to achieve full functionality, depending on your network layout. Read about UDP broadcasts for more information.}. If you want to disable this feature, define the \texttt{TRACY\_NO\_BROADCAST} macro.

\subsubsection{Client network interface}

By default, the Tracy client will listen on all network interfaces. If you want to restrict it to only listening on the localhost interface, define the \texttt{TRACY\_ONLY\_LOCALHOST} macro at compile-time, or set the \texttt{TRACY\_ONLY\_LOCALHOST} environment variable to $1$ at runtime.

By default, the Tracy client will listen on IPv6 interfaces, falling back to IPv4 only if IPv6 is unavailable. If you want to restrict it to only listening on IPv4 interfaces, define the \texttt{TRACY\_ONLY\_IPV4} macro at compile-time, or set the \texttt{TRACY\_ONLY\_IPV4} environment variable to $1$ at runtime.

\subsubsection{Setup for multi-DLL projects}

Things are a bit different in projects that consist of multiple DLLs/shared objects. Compiling \texttt{TracyClient.cpp} into every DLL is not an option because this would result in several instances of Tracy objects lying around in the process. We instead need to pass their instances to the different DLLs to be reused there.

For that, you need a \emph{profiler DLL} to which your executable and the other DLLs link. If that doesn't exist, you have to create one explicitly for Tracy\footnote{You may also look at the \texttt{library} directory in the profiler source tree.}. This library should contain the \texttt{public/TracyClient.cpp} source file. Link the executable and all DLLs you want to profile to this DLL.

If you are targeting Windows with Microsoft Visual Studio or MinGW, add the \texttt{TRACY\_IMPORTS} define to your application.

If you are experiencing crashes or freezes when manually loading/unloading a separate DLL with Tracy integration, you might want to try defining both \texttt{TRACY\_DELAYED\_INIT} and \texttt{TRACY\_MANUAL\_LIFETIME} macros.

\texttt{TRACY\_DELAYED\_INIT} enables a path where profiler data is gathered into one structure and initialized on the first request rather than statically at the DLL load at the expense of atomic load on each request to the profiler data. \texttt{TRACY\_MANUAL\_LIFETIME} flag augments this behavior to provide manual \texttt{StartupProfiler} and \texttt{ShutdownProfiler} functions that allow you to create and destroy the profiler data manually. This manual management removes the need to do an atomic load on each call and lets you define an appropriate place to free the resources.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Keep everything consistent}
When working with multiple libraries, it is easy to make a mistake and use different sets of feature macros between any two compilation jobs. If you do so, Tracy will not be able to work correctly, and there will be no error or warning messages about the problem. Henceforth, you must make sure each shared object you want to link with, or load uses the same set of macro definitions.

Please note that using a prebuilt shared Tracy library, as provided by some package manager or system distribution, also qualifies as using multiple libraries.
\end{bclogo}

\subsubsection{Problematic platforms}

In the case of some programming environments, you may need to take extra steps to ensure Tracy can work correctly.

\paragraph{Microsoft Visual Studio}

If you are using MSVC, you will need to disable the \emph{Edit And Continue} feature, as it makes the compiler non-conformant to some aspects of the C++ standard. In order to do so, open the project properties and go to \menu[,]{C/C++,General,Debug Information Format} and make sure \emph{Program Database for Edit And Continue (/ZI)} is \emph{not} selected.

\paragraph{Universal Windows Platform}

Due to a restricted access to Win32 APIs and other sandboxing issues (like network isolation), several limitations apply to using Tracy in a UWP application compared to Windows Desktop:

\begin{itemize}
\item Call stack sampling is not available.
\item System profiling is not available.
\item To be able to connect from another machine on the local network, the app needs the \emph{privateNetworkClientServer} capability. To connect from localhost, an active inbound loopback exemption is also necessary\footnote{\url{https://docs.microsoft.com/en-us/windows/uwp/communication/interprocess-communication\#loopback}}.
\end{itemize}

\paragraph{Apple woes}

Because Apple \emph{has} to be \emph{think different}, there are some problems with using Tracy on OSX and iOS. First, the performance hit due to profiling is higher than on other platforms. Second, some critical features are missing and won't be possible to achieve:

\begin{itemize}
\item There's no support for the \texttt{TRACY\_NO\_EXIT} mode.
\item Profiling is interrupted when the application exits. This will result in missing zones, memory allocations, or even source location names.
\item OpenGL can't be profiled.
\end{itemize}

\paragraph{Android lunacy}
\label{androidlunacy}

Starting with Android 8.0, you are no longer allowed to use the \texttt{/proc} file system. One of the consequences of this change is the inability to check system CPU usage.

This is apparently a security enhancement. Unfortunately, in its infinite wisdom, Google has decided not to give you an option to bypass this restriction.

To workaround this limitation, you will need to have a rooted device. Execute the following commands using \texttt{root} shell:

\begin{lstlisting}[language=sh]
setenforce 0
mount -o remount,hidepid=0 /proc
echo -1 > /proc/sys/kernel/perf_event_paranoid
echo 0 > /proc/sys/kernel/kptr_restrict
\end{lstlisting}

The first command will allow access to system CPU statistics. The second one will enable inspection of foreign processes (required for context switch capture). The third one will lower restrictions on access to performance counters. The last one will allow retrieval of kernel symbol pointers. \emph{Be sure that you are fully aware of the consequences of making these changes.}

\paragraph{Virtual machines}

The best way to run Tracy is on bare metal. Avoid profiling applications in virtualized environments, including services provided in the cloud. Virtualization interferes with the critical facilities needed for the profiler to work, influencing the results you get. Possible problems may vary, depending on the configuration of the VM, and include:

\begin{itemize}
\item Reduced precision of time stamps.
\item Inability to obtain precise timestamps, resulting in error messages such as \emph{CPU doesn't support RDTSC instruction}, or \emph{CPU doesn't support invariant TSC}. On Windows, you can work this around by rebuilding the profiled application with the \texttt{TRACY\_TIMER\_QPC} define, which severely lowers the resolution of time readings.
\item Frequency of call stack sampling may be reduced.
\item Call stack sampling might lack time stamps. While you can use such a reduced data set to perform statistical analysis, you won't be able to limit the time range or see the sampling zones on the timeline.
\end{itemize}

\subsubsection{Changing network port}

By default, the client and server communicate on the network using port 8086. The profiling session utilizes the TCP protocol, and the client sends presence announcement broadcasts over UDP.

Suppose for some reason you want to use another port\footnote{For example, other programs may already be using it, or you may have overzealous firewall rules, or you may want to run two clients on the same IP address.}. In that case, you can change it using the \texttt{TRACY\_DATA\_PORT} macro for the data connection and \texttt{TRACY\_BROADCAST\_PORT} macro for client broadcasts. Alternatively, you may change both ports at the same time by declaring the \texttt{TRACY\_PORT} macro (specific macros listed before have higher priority). You may also change the data connection port without recompiling the client application by setting the \texttt{TRACY\_PORT} environment variable.

If a custom port is not specified and the default listening port is already occupied, the profiler will automatically try to listen on a number of other ports.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Important}
To enable network communication, Tracy needs to open a listening port. Make sure it is not blocked by an overzealous firewall or anti-virus program.
\end{bclogo}

\subsubsection{Limitations}

When using Tracy Profiler, keep in mind the following requirements:

\begin{itemize}
\item The application may use each lock in no more than 64 unique threads.
\item There can be no more than 65534 unique source locations\footnote{A source location is a place in the code, which is identified by source file name and line number, for example, when you markup a zone.}. This number is further split in half between native code source locations and dynamic source locations (for example, when Lua instrumentation is used).
\item If there are recursive zones at any point in a zone stack, each unique zone source location should not appear more than 255 times.
\item Profiling session cannot be longer than 1.6 days ($2^{47}$ \si{\nano\second}). This also includes on-demand sessions.
\item No more than 4 billion ($2^{32}$) memory free events may be recorded.
\item No more than 16 million ($2^{24}$) unique call stacks can be captured.
\end{itemize}

The following conditions also need to apply but don't trouble yourself with them too much. You would probably already know if you'd be breaking any.

\begin{itemize}
\item Only little-endian CPUs are supported.
\item Virtual address space must be limited to 48 bits.
\item Tracy server requires CPU which can handle misaligned memory accesses.
\end{itemize}

\subsection{Check your environment}

It is not an easy task to reliably measure the performance of an application on modern machines. There are many factors affecting program execution characteristics, some of which you will be able to minimize and others you will have to live with. It is critically important that you understand how these variables impact profiling results, as it is key to understanding the data you get.

\subsubsection{Operating system}
\label{checkenvironmentos}

In a multitasking operating system, applications compete for system resources with each other. This has a visible effect on the measurements performed by the profiler, which you may or may not accept.

To get the most accurate profiling results, you should minimize interference caused by other programs running on the same machine. Before starting a profile session, close all web browsers, music players, instant messengers, and all other non-essential applications like Steam, Uplay, etc. Make sure you don't have the debugger hooked into the profiled program, as it also impacts the timing results.

Interference caused by other programs can be seen in the profiler if context switch capture (section~\ref{contextswitches}) is enabled.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bclampe
]{Debugger in Visual Studio}
In MSVC, you would typically run your program using the \emph{Start Debugging} menu option, which is conveniently available as a \keys{F5} shortcut. You should instead use the \emph{Start Without Debugging} option, available as \keys{\ctrl + F5} shortcut.
\end{bclogo}

\subsubsection{CPU design}
\label{checkenvironmentcpu}

Where to even begin here? Modern processors are such complex beasts that it's almost impossible to say anything about how they will behave surely. Cache configuration, prefetcher logic, memory timings, branch predictor, execution unit counts are all the drivers of instructions-per-cycle uplift nowadays after the megahertz race had hit the wall. Not only is it challenging to reason about, but you also need to take into account how the CPU topology affects things, which is described in more detail in section~\ref{cputopology}.

Nevertheless, let's look at how we can try to stabilize the profiling data.

\paragraph{Superscalar out-of-order speculative execution}

Also known as: the \emph{spectre} thing we have to deal with now.

You must be aware that most processors available on the market\footnote{Except low-cost ARM CPUs.} \emph{do not} execute machine code linearly, as laid out in the source code. This can lead to counterintuitive timing results reported by Tracy. Trying to get more 'reliable' readings\footnote{And by saying 'reliable,' you do in reality mean: behaving in a way you expect it.} would require a change in the behavior of the code, and this is not a thing a profiler should do. So instead, Tracy shows you what the hardware is \emph{really} doing.

This is a complex subject, and the details vary from one CPU to another. You can read a brief rundown of the topic at the following address: \url{https://travisdowns.github.io/blog/2019/06/11/speed-limits.html}.

\paragraph{Simultaneous multithreading}

Also known as: Hyper-threading. Typically present on Intel and AMD processors.

To get the most reliable results, you should have all the CPU core resources dedicated to a single thread of your program. Otherwise, you're no longer measuring the behavior of your code but rather how it keeps up when its computing resources are randomly taken away by some other thing running on another pipeline within the same physical core.

Note that you might \emph{want} to observe this behavior if you plan to deploy your application on a machine with simultaneous multithreading enabled. This would require careful examination of what else is running on the machine, or even how the operating system schedules the threads of your own program, as various combinations of competing workloads (e.g., integer/floating-point operations) will be impacted differently.

\paragraph{Turbo mode frequency scaling}

Also known as: Turbo Boost (Intel), Precision Boost (AMD).

While the CPU is more-or-less designed always to be able to work at the advertised \emph{base} frequency, there is usually some headroom left, which allows usage of the built-in automatic overclocking. There are no guarantees that the CPU can attain the turbo frequencies or how long it will uphold them, as there are many things to take into consideration:

\begin{itemize}
\item How many cores are in use? Just one, or all 8? All 16?
\item What type of work is being performed? Integer? Floating-point? 128-wide SIMD? 256-wide SIMD? 512-wide SIMD?
\item Were you lucky in the silicon lottery? Some dies are just better made and can achieve higher frequencies.
\item Are you running on the best-rated core or at the worst-rated core? Some cores may be unable to match the performance of other cores in the same processor.
\item What kind of cooling solution are you using? The cheap one bundled with the CPU or a hefty chunk of metal that has no problem with heat dissipation?
\item Do you have complete control over the power profile? Spoiler alert: no. The operating system may run anything at any time on any of the other cores, which will impact the turbo frequency you're able to achieve.
\end{itemize}

As you can see, this feature basically screams 'unreliable results!' Best keep it disabled and run at the base frequency. Otherwise, your timings won't make much sense. A true example: branchless compression function executing multiple times with the same input data was measured executing at \emph{four} different speeds.

Keep in mind that even at the base frequency, you may hit the thermal limits of the silicon and be down throttled.

\paragraph{Power saving}

This is, in essence, the same as turbo mode, but in reverse. While unused, processor cores are kept at lower frequencies (or even wholly disabled) to reduce power usage. When your code starts running\footnote{Not necessarily when the application is started, but also when, for example, a blocking mutex becomes released by other thread and is acquired.}, the core frequency needs to ramp up, which may be visible in the measurements.

Even worse, if your code doesn't do a lot of work (for example, because it is waiting for the GPU to finish rendering the frame), the CPU might not ramp up the core frequency to 100\%, which will skew the results.

Again, to get the best results, keep this feature disabled.

\paragraph{AVX offset and power licenses}

Intel CPUs are unable to run at their advertised frequencies when they perform wide SIMD operations due to increased power requirements\footnote{AMD processors are not affected by this issue.}. Therefore, depending on the width \emph{and} type of operations executed, the core operating frequency will be reduced, in some cases quite drastically\footnote{\url{https://en.wikichip.org/wiki/intel/xeon_gold/5120\#Frequencies}}. To make things even better, \emph{some} parts of the workload will execute within the available power license, at a twice reduced processing rate. After that, the CPU may be stopped for some time so that the wide parts of executions units can be powered up. Then the work will continue at full processing rate but at a reduced frequency.

Be very careful when using AVX2 or AVX512.

More information can be found at \url{https://travisdowns.github.io/blog/2020/01/17/avxfreq1.html}, \url{https://en.wikichip.org/wiki/intel/frequency_behavior}.

\paragraph{Summing it up}
\label{ryzen}

Power management schemes employed in various CPUs make it hard to reason about the true performance of the code. For example, figure~\ref{ryzenimage} contains a histogram of function execution times (as described in chapter~\ref{findzone}), as measured on an AMD Ryzen CPU. The results ranged from 13.05~\si{\micro\second} to 61.25~\si{\micro\second} (extreme outliers were not included on the graph, limiting the longest displayed time to 36.04~\si{\micro\second}).

\begin{figure}[h]
\centering
\includegraphics[width=0.5\textwidth]{images/ryzen.png}
\caption{Example function execution times on a Ryzen CPU}
\label{ryzenimage}
\end{figure}

We can immediately see that there are two distinct peaks, at 13.4~\si{\micro\second} and 15.3~\si{\micro\second}. A reasonable assumption would be that there are two paths in the code, one that can omit some work, and the second one which must do some additional job. But here's a catch -- the measured code is actually branchless and always executes the same way. The two peaks represent two turbo frequencies between which the CPU was aggressively switching.

We can also see that the graph gradually falls off to the right (representing longer times), with a slight bump near the end. Again, this can be attributed to running in power-saving mode, with different reaction times to the required operating frequency boost to full power.

\subsection{Building the server}
\label{buildingserver}

The easiest way to get going is to build the data analyzer, available in the \texttt{profiler} directory. Then, you can connect to localhost or remote clients and view the collected data right away with it.

If you prefer to inspect the data only after a trace has been performed, you may use the command-line utility in the \texttt{capture} directory. It will save a data dump that you may later open in the graphical viewer application.

Ideally, it would be best to use the same version of the Tracy profiler on both client and server. The network protocol may change in-between releases, in which case you won't be able to make a connection.

See section~\ref{capturing} for more information about performing captures.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Important}
Due to the memory requirements for data storage, the Tracy server is only supposed to run on 64-bit platforms. While nothing prevents the program from building and executing in a 32-bit environment, doing so is not supported.
\end{bclogo}

\subsubsection{Required libraries}

To build the application contained in the \texttt{profiler} directory, you will need to install external libraries, which are not bundled with Tracy.

\subparagraph{Capstone library} At the time of writing, the capstone library is in a bit of disarray. The officially released version 4.0.2 can't disassemble some AVX instructions, which are successfully parsed by the \texttt{next} branch. However, the \texttt{next} branch somehow lost information about input/output registers for some functions. You may want to explore the various available versions to find one that suits your needs the best. Note that only the \texttt{next} branch is actively maintained. Be aware that your package manager might distribute the deprecated \texttt{master} branch.

\paragraph{Windows}

On Windows, you will need to use the \texttt{vcpkg} utility. If you are not familiar with this tool, please read the description at the following address: \url{https://docs.microsoft.com/en-us/cpp/build/vcpkg}.

There are two ways you can run \texttt{vcpkg} to install the dependencies for Tracy:

\begin{itemize}
\item Local installation within the project directory -- run this script to download and build both \texttt{vcpkg} and the required dependencies:
\begin{lstlisting}[language=sh]
vcpkg\install_vcpkg_dependencies.bat
\end{lstlisting}
This writes files only to the \texttt{vcpkg\textbackslash{}vcpkg} directory and makes no other changes on your machine.
\item System-wide installation with Manifest mode -- install \texttt{vcpkg} by following the instructions on its website, make sure that the environment variable \texttt{VCPKG\_ROOT} is set to the path where you have clone the repository, and then execute the following command:
\begin{lstlisting}[language=sh]
vcpkg integrate install
\end{lstlisting}
After this step, you can use any Visual Studio project files to build as usual.
Dependencies will be installed automatically based on vcpkg manifest listing (the \texttt{vcpkg.json} file at repository root).
For more information about vcpkg manifest mode in Visual Studio, you can read more details at the following address: \url{https://vcpkg.io/en/docs/users/manifests.html#msbuild-integration}.
\end{itemize}

\paragraph{Unix}

On Unix systems you will need to install the \texttt{pkg-config} utility and the following libraries: \texttt{glfw}, \texttt{freetype}, \texttt{capstone}, \texttt{dbus}. Some Linux distributions will require you to add a \texttt{lib} prefix and a \texttt{-dev}, or \texttt{-devel} postfix to library names. You may also need to add a seemingly random number to the library name (for example: \texttt{freetype2}, or \texttt{freetype6}). Be aware that your package manager might distribute the deprecated \texttt{master}-branch version of \texttt{capstone}, and a build from source from the \texttt{next}-branch might be necessary for you. Have fun!

In addition to the beforementioned libraries, you might also have to install the \texttt{tbb} library\footnote{Technically this is not a dependency of Tracy but rather of \texttt{libstdc++} but it may still not be installed by default.}.

Installation of the libraries on OSX can be facilitated using the \texttt{brew} package manager.

\subparagraph{Wayland}

Linux builds of Tracy use the Wayland protocol by default, which allows proper support for Hi-DPI scaling and high-precision input devices such as touchpads. As such, the \texttt{glfw} library is no longer needed, but you will have to install \texttt{libxkbcommon}, \texttt{wayland}, \texttt{libglvnd} (or \texttt{libegl} on some distributions).

You can build the profiler the old way on Linux by enabling the \texttt{LEGACY} flag, e.g. by issuing the following build command \texttt{make LEGACY=1}.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Window decorations}
Please don't ask about window decorations in Gnome. The current behavior is the intended behavior. Gnome does not want windows to have decorations, and Tracy respects that choice. If you find this problematic, use a desktop environment that actually listens to its users.
\end{bclogo}

\subsubsection{Build process}

As mentioned earlier, each utility is contained in its own directory, for example \texttt{profiler} or \texttt{capture}\footnote{Other utilities are contained in the \texttt{csvexport}, \texttt{import-chrome} and \texttt{update} directories.}. Where do you go within these directories depends on the operating system you are using.

On Windows navigate to the \texttt{build/win32} directory and open the solution file in Visual Studio. On Unix go to the \texttt{build/unix} directory and build the \texttt{release} target using GNU make.

\subsubsection{Embedding the server in profiled application}
\label{embeddingserver}

While not officially supported, it is possible to embed the server in your application, the same one running the client part of Tracy. How to make this work is left up for you to figure out.

Note that most libraries bundled with Tracy are modified in some way and contained in the \texttt{tracy} namespace. The one exception is Dear ImGui, which can be freely replaced.

Be aware that while the Tracy client uses its own separate memory allocator, the server part of Tracy will use global memory allocation facilities shared with the rest of your application. This will affect both the memory usage statistics and Tracy memory profiling.

The following defines may be of interest:

\begin{itemize}
\item \texttt{TRACY\_NO\_FILESELECTOR} -- controls whether a system load/save dialog is compiled in. If it's enabled, the saved traces will be named \texttt{trace.tracy}.
\item \texttt{TRACY\_NO\_STATISTICS} -- Tracy will perform statistical data collection on the fly, if this macro is \emph{not} defined. This allows extended trace analysis (for example, you can perform a live search for matching zones) at a small CPU processing cost and a considerable memory usage increase (at least 8 bytes per zone).
\item \texttt{TRACY\_NO\_ROOT\_WINDOW} -- the main profiler view won't occupy the whole window if this macro is defined. Additional setup is required for this to work. If you want to embed the server into your application, you probably should enable this option.
\end{itemize}

\subsubsection{DPI scaling}

The graphic server application will adapt to the system DPI scaling. If for some reason, this doesn't work in your case, you may try setting the \texttt{TRACY\_DPI\_SCALE} environment variable to a scale fraction, where a value of 1 indicates no scaling.

\subsection{Naming threads}
\label{namingthreads}

Remember to set thread names for proper identification of threads. You should do so by using the function \texttt{tracy::SetThreadName(name)} exposed in the \texttt{public/common/TracySystem.hpp} header, as the system facilities typically have limited functionality.

Tracy will try to capture thread names through operating system data if context switch capture is active. However, this is only a fallback mechanism, and it shouldn't be relied upon.

\subsubsection{Source location data customization}

Some source location data such as function name, file path or line number can be overriden with defines \texttt{TracyFunction}, \texttt{TracyFile}, \texttt{TracyLine}\footnote{By default the macros unwrap to \texttt{\_\_FUNCTION\_\_}, \texttt{\_\_FILE\_\_} and \texttt{\_\_LINE\_\_} respectively.} made before including \texttt{public/tracy/Tracy.hpp} header file\footnote{You should add either \texttt{public} or \texttt{public/tracy} directory from the Tracy root to the include directories list in your project. Then you will be able to \texttt{\#include "tracy/Tracy.hpp"} or \texttt{\#include "Tracy.hpp"}, respectively.}.

\begin{lstlisting}
#if defined(__clang__) || defined(__GNUC__)
#  define TracyFunction __PRETTY_FUNCTION__
#elif defined(_MSC_VER)
#  define TracyFunction __FUNCSIG__
#endif

#include <tracy/Tracy.hpp>

...

void Graphics::Render()
{
    ZoneScoped;
    ...
}
\end{lstlisting}

\subsection{Crash handling}
\label{crashhandling}

On selected platforms (see section~\ref{featurematrix}) Tracy will intercept application crashes\footnote{For example, invalid memory accesses ('segmentation faults', 'null pointer exceptions'), divisions by zero, etc.}. This serves two purposes. First, the client application will be able to send the remaining profiling data to the server. Second, the server will receive a crash report with the crash reason, call stack at the time of the crash, etc.

This is an automatic process, and it doesn't require user interaction. If you are experiencing issues with crash handling you may want to try defining the \texttt{TRACY\_NO\_CRASH\_HANDLER} macro to disable the built in crash handling.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcattention
]{Caveats}
\begin{itemize}
\item On MSVC the debugger has priority over the application in handling exceptions. If you want to finish the profiler data collection with the debugger hooked-up, select the \emph{continue} option in the debugger pop-up dialog.
\item On Linux, crashes are handled with signals. Tracy needs to have \texttt{SIGPWR} available, which is rather rarely used. Still, the program you are profiling may expect to employ it for its purposes, which would cause a conflict\footnote{For example, Mono may use it to trigger garbage collection.}. To workaround such cases, you may set the \texttt{TRACY\_CRASH\_SIGNAL} macro value to some other signal (see \texttt{man 7 signal} for a list of signals). Ensure that you avoid conflicts by selecting a signal that the application wouldn't usually receive or emit.
\end{itemize}
\end{bclogo}

\subsection{Feature support matrix}
\label{featurematrix}

Some features of the profiler are only available on selected platforms. Please refer to table~\ref{featuretable} for details.

\begin{table}[h]
\centering
\begin{tabular}[h]{c|c|c|c|c|c|c}
\textbf{Feature} & \textbf{Windows} & \textbf{Linux} & \textbf{Android} & \textbf{OSX} & \textbf{iOS} & \textbf{BSD} \\ \hline
Profiling program init & \faCheck & \faCheck & \faCheck & \faPoo & \faPoo & \faCheck \\
CPU zones & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck \\
Locks & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck \\
Plots & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck \\
Messages & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck \\
Memory & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck \\
GPU zones (OpenGL) & \faCheck & \faCheck & \faCheck & \faPoo & \faPoo & \\
GPU zones (Vulkan) & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck & \\
Call stacks & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck \\
Symbol resolution & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck \\
Crash handling & \faCheck & \faCheck & \faCheck & \faTimes & \faTimes & \faTimes \\
CPU usage probing & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck & \faCheck \\
Context switches & \faCheck & \faCheck & \faCheck & \faTimes & \faPoo & \faTimes \\
Wait stacks & \faCheck & \faCheck & \faCheck & \faTimes & \faPoo & \faTimes \\
CPU topology information & \faCheck & \faCheck & \faCheck & \faTimes & \faTimes & \faTimes \\
Call stack sampling & \faCheck & \faCheck & \faCheck & \faTimes & \faPoo & \faTimes \\
Hardware sampling & \faCheck{}\textsuperscript{\emph{a}} & \faCheck & \faCheck & \faTimes & \faPoo & \faTimes \\
VSync capture & \faCheck & \faCheck & \faTimes & \faTimes & \faTimes & \faTimes \\
\end{tabular}

\vspace{1em}
\faPoo{} -- Not possible to support due to platform limitations. \\
\textsuperscript{\emph{a}}Possible through WSL2.
\caption{Feature support matrix}
\label{featuretable}
\end{table}

\section{Client markup}
\label{client}

With the steps mentioned above, you will be able to connect to the profiled program, but there probably won't be any data collection performed\footnote{With some small exceptions, see section~\ref{automated}.}. Unless you're able to perform automatic call stack sampling (see chapter~\ref{sampling}), you will have to instrument the application manually. All the user-facing interface is contained in the \texttt{public/tracy/Tracy.hpp} header file\footnote{You should add either \texttt{public} or \texttt{public/tracy} directory from the Tracy root to the include directories list in your project. Then you will be able to \texttt{\#include "tracy/Tracy.hpp"} or \texttt{\#include "Tracy.hpp"}, respectively.}.

Manual instrumentation is best started with adding markup to the application's main loop, along with a few functions that the loop calls. Such an approach will give you a rough outline of the function's time cost, which you may then further refine by instrumenting functions deeper in the call stack. Alternatively, automated sampling might guide you more quickly to places of interest.

\subsection{Handling text strings}
\label{textstrings}

When dealing with Tracy macros, you will encounter two ways of providing string data to the profiler. In both cases, you should pass \texttt{const char*} pointers, but there are differences in the expected lifetime of the pointed data.

\begin{enumerate}
\item When a macro only accepts a pointer (for example: \texttt{TracyMessageL(text)}), the provided string data must be accessible at any time in program execution (\emph{this also includes the time after exiting the \texttt{main} function}). The string also cannot be changed. This basically means that the only option is to use a string literal (e.g.: \texttt{TracyMessageL("Hello")}).

\item If there's a string pointer with a size parameter (for example \texttt{TracyMessage(text, size)}), the profiler will allocate a temporary internal buffer to store the data. The \texttt{size} count should not include the terminating null character, using \texttt{strlen(text)} is fine. The pointed-to data is not used afterward. Remember that allocating and copying memory involved in this operation has a small time cost.
\end{enumerate}

Be aware that every single instance of text string data passed to the profiler can't be larger than 64 KB.

\subsubsection{Program data lifetime}
\label{datalifetime}

Take extra care to consider the lifetime of program code (which includes string literals) in your application. For example, if you dynamically add and remove modules (i.e., DLLs, shared objects) during the runtime, text data will only be present when the module is loaded. Additionally, when a module is unloaded, the operating system can place another one in its space in the process memory map, resulting in the aliasing of text strings. This leads to all sorts of confusion and potential crashes.

Note that string literals are the only option in many parts of the Tracy API. For example, look at how frame or plot names are specified. You cannot unload modules that contain string literals that you passed to the profiler\footnote{If you really do must unload a module, manually allocating a \texttt{char} buffer, as described in section~\ref{uniquepointers}, will give you a persistent string in memory.}.

\subsubsection{Unique pointers}
\label{uniquepointers}

In some cases marked in the manual, Tracy expects you to provide a unique pointer in each occurrence the same string literal is used. This can be exemplified in the following listing:

\begin{lstlisting}
FrameMarkStart("Audio processing");
...
FrameMarkEnd("Audio processing");
\end{lstlisting}

Here, we pass two string literals with identical contents to two different macros. It is entirely up to the compiler to decide if it will pool these two strings into one pointer or if there will be two instances present in the executable image\footnote{\cite{ISO:2012:III} \S 2.14.5.12: "Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation-defined."}. For example, on MSVC, this is controlled by \menu[,]{Configuration Properties,C/C++,Code Generation,Enable String Pooling} option in the project properties (optimized builds enable it automatically). Note that even if string pooling is used on the compilation unit level, it is still up to the linker to implement pooling across object files.

As you can see, making sure that string literals are properly pooled can be surprisingly tricky. To work around this problem, you may employ the following technique. In \emph{one} source file create the unique pointer for a string literal, for example:

\begin{lstlisting}
const char* const sl_AudioProcessing = "Audio processing";
\end{lstlisting}

Then in each file where you want to use the literal, use the variable name instead. Notice that if you'd like to change a name passed to Tracy, you'd need to do it only in one place with such an approach.

\begin{lstlisting}
extern const char* const sl_AudioProcessing;

FrameMarkStart(sl_AudioProcessing);
...
FrameMarkEnd(sl_AudioProcessing);
\end{lstlisting}

In some cases, you may want to have semi-dynamic strings. For example, you may want to enumerate workers but don't know how many will be used. You can handle this by allocating a never-freed \texttt{char} buffer, which you can then propagate where it's needed. For example:

\begin{lstlisting}
char* workerId = new char[16];
snprintf(workerId, 16, "Worker %i", id);
...
FrameMarkStart(workerId);
\end{lstlisting}

You have to make sure it's initialized only once, before passing it to any Tracy API, that it is not overwritten by new data, etc. In the end, this is just a pointer to character-string data. It doesn't matter if the memory was loaded from the program image or allocated on the heap.

\subsection{Specifying colors}

In some cases, you will want to provide your own colors to be displayed by the profiler. You should use a hexadecimal \texttt{0xRRGGBB} notation in all such places.

Alternatively you may use named colors predefined in \texttt{common/TracyColor.hpp} (included by \texttt{Tracy.hpp}). Visual reference: \url{https://en.wikipedia.org/wiki/X11_color_names}.

Do not use \texttt{0x000000} if you want to specify black color, as zero is a special value indicating that no color was set. Instead, use a value close to zero, e.g. \texttt{0x000001}.

\subsection{Marking frames}
\label{markingframes}

To slice the program's execution recording into frame-sized chunks\footnote{Each frame starts immediately after previous has ended.}, put the \texttt{FrameMark} macro after you have completed rendering the frame. Ideally, that would be right after the swap buffers command.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bclampe
]{Do I need this?}
This step is optional, as some applications do not use the concept of a frame.
\end{bclogo}

\subsubsection{Secondary frame sets}
\label{secondaryframeset}

In some cases, you may want to track more than one set of frames in your program. To do so, you may use the \texttt{FrameMarkNamed(name)} macro, which will create a new set of frames for each unique name you provide. But, first, make sure you are correctly pooling the passed string literal, as described in section~\ref{uniquepointers}.

\subsubsection{Discontinuous frames}

Some types of frames are discontinuous by their nature -- they are executed periodically, with a pause between each run. Examples of such frames are a physics processing step in a game loop or an audio callback running on a separate thread. Tracy can also track this kind of frames.

To mark the beginning of a discontinuous frame use the \texttt{FrameMarkStart(name)} macro. After the work is finished, use the \texttt{FrameMarkEnd(name)} macro.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Important}
\begin{itemize}
\item Frame types \emph{must not} be mixed. For each frame set, identified by an unique name, use either continuous or discontinuous frames only!
\item You \emph{must} issue the \texttt{FrameMarkStart} and \texttt{FrameMarkEnd} macros in proper order. Be extra careful, especially if multi-threading is involved.
\item String literals passed as frame names must be properly pooled, as described in section~\ref{uniquepointers}.
\end{itemize}
\end{bclogo}

\subsubsection{Frame images}
\label{frameimages}

It is possible to attach a screen capture of your application to any frame in the main frame set. This can help you see the context of what's happening in various places in the trace. You need to implement retrieval of the image data from GPU by yourself.

Images are sent using the \texttt{FrameImage(image, width, height, offset, flip)} macro, where \texttt{image} is a pointer to RGBA\footnote{Alpha value is ignored, but leaving it out wouldn't map well to the way graphics hardware works.} pixel data, \texttt{width} and \texttt{height} are the image dimensions, which \emph{must be divisible by 4}, \texttt{offset} specifies how much frame lag was there for the current image (see chapter~\ref{screenshotcode}), and \texttt{flip} should be set, if the graphics API stores images upside-down\footnote{For example, OpenGL flips images, but Vulkan does not.}. The profiler copies the image data, so you don't need to retain it.

Handling image data requires a lot of memory and bandwidth\footnote{One uncompressed 1080p image takes 8 MB.}. To achieve sane memory usage, you should scale down taken screenshots to a suitable size, e.g., $320\times180$.

To further reduce image data size, frame images are internally compressed using the DXT1 Texture Compression technique\footnote{\url{https://en.wikipedia.org/wiki/S3_Texture_Compression}}, which significantly reduces data size\footnote{One pixel is stored in a nibble (4 bits) instead of 32 bits.}, at a slight quality decrease. The compression algorithm is high-speed and can be made even faster by enabling SIMD processing, as indicated in table~\ref{EtcSimd}.

\begin{table}[h]
\centering
\begin{tabular}[h]{c|c|c}
\textbf{Implementation} & \textbf{Required define} & \textbf{Time} \\ \hline
x86 Reference & --- & 198.2 \si{\micro\second} \\
x86 SSE4.1\textsuperscript{a} & \texttt{\_\_SSE4\_1\_\_} & 25.4 \si{\micro\second} \\
x86 AVX2 & \texttt{\_\_AVX2\_\_} & 17.4 \si{\micro\second} \\
ARM Reference & --- & 1.04 \si{\milli\second} \\
ARM32 NEON\textsuperscript{b} & \texttt{\_\_ARM\_NEON} & 529 \si{\micro\second} \\
ARM64 NEON & \texttt{\_\_ARM\_NEON} & 438 \si{\micro\second}
\end{tabular}

\vspace{1em}
\textsuperscript{a)} VEX encoding; \hspace{0.5em} \textsuperscript{b)} ARM32 NEON code compiled for ARM64
\caption{Client compression time of $320\times180$ image. x86: Ryzen 9 3900X (MSVC); ARM: ODROID-C2 (gcc).}
\label{EtcSimd}
\end{table}

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcattention
]{Caveats}
\begin{itemize}
\item Frame images are compressed on a second client profiler thread\footnote{Small part of compression task is offloaded to the server.}, to reduce memory usage of queued images. This might have an impact on the performance of the profiled application.
\item This second thread will be periodically woken up, even if there are no frame images to compress\footnote{This way of doing things is required to prevent a deadlock in specific circumstances.}. If you are not using the frame image capture functionality and you don't wish this thread to be running, you can define the \texttt{TRACY\_NO\_FRAME\_IMAGE} macro.
\item Due to implementation details of the network buffer, a single frame image cannot be greater than 256 KB after compression. Note that a $960\times540$ image fits in this limit.
\end{itemize}
\end{bclogo}

\paragraph{OpenGL screen capture code example}
\label{screenshotcode}

There are many pitfalls associated with efficiently retrieving screen content. For example, using \texttt{glReadPixels} and then resizing the image using some library is terrible for performance, as it forces synchronization of the GPU to CPU and performs the downscaling in software. To do things properly, we need to scale the image using the graphics hardware and transfer data asynchronously, which allows the GPU to run independently of the CPU.

The following example shows how this can be achieved using OpenGL 3.2. Of course, more recent OpenGL versions allow doing things even better (for example, using persistent buffer mapping), but this manual won't cover it here.

Let's begin by defining the required objects. First, we need a \emph{texture} to store the resized image, a \emph{framebuffer object} to be able to write to the texture, a \emph{pixel buffer object} to store the image data for access by the CPU, and a \emph{fence} to know when the data is ready for retrieval. We need everything in \emph{at least} three copies (we'll use four) because the rendering, as seen in the program, can run ahead of the GPU by a couple of frames. Next, we need an index to access the appropriate data set in a ring-buffer manner. And finally, we need a queue to store indices to data sets that we are still waiting for.

\begin{lstlisting}
GLuint m_fiTexture[4];
GLuint m_fiFramebuffer[4];
GLuint m_fiPbo[4];
GLsync m_fiFence[4];
int m_fiIdx = 0;
std::vector<int> m_fiQueue;
\end{lstlisting}

Everything needs to be correctly initialized (the cleanup is left for the reader to figure out).

\begin{lstlisting}
glGenTextures(4, m_fiTexture);
glGenFramebuffers(4, m_fiFramebuffer);
glGenBuffers(4, m_fiPbo);
for(int i=0; i<4; i++)
{
    glBindTexture(GL_TEXTURE_2D, m_fiTexture[i]);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 320, 180, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);

    glBindFramebuffer(GL_FRAMEBUFFER, m_fiFramebuffer[i]);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
		m_fiTexture[i], 0);

    glBindBuffer(GL_PIXEL_PACK_BUFFER, m_fiPbo[i]);
    glBufferData(GL_PIXEL_PACK_BUFFER, 320*180*4, nullptr, GL_STREAM_READ);
}
\end{lstlisting}

We will now set up a screen capture, which will downscale the screen contents to $320\times180$ pixels and copy the resulting image to a buffer accessible by the CPU when the operation is done. This should be placed right before \emph{swap buffers} or \emph{present} call.

\begin{lstlisting}
assert(m_fiQueue.empty() || m_fiQueue.front() != m_fiIdx);	// check for buffer overrun
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fiFramebuffer[m_fiIdx]);
glBlitFramebuffer(0, 0, res.x, res.y, 0, 0, 320, 180, GL_COLOR_BUFFER_BIT, GL_LINEAR);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fiFramebuffer[m_fiIdx]);
glBindBuffer(GL_PIXEL_PACK_BUFFER, m_fiPbo[m_fiIdx]);
glReadPixels(0, 0, 320, 180, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
m_fiFence[m_fiIdx] = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
m_fiQueue.emplace_back(m_fiIdx);
m_fiIdx = (m_fiIdx + 1) % 4;
\end{lstlisting}

And lastly, just before the capture setup code that was just added\footnote{Yes, before. We are handling past screen captures here.} we need to have the image retrieval code. We are checking if the capture operation has finished. If it has, we map the \emph{pixel buffer object} to memory, inform the profiler that there are image data to be handled, unmap the buffer and go to check the next queue item. If capture is still pending, we break out of the loop. We will have to wait until the next frame to check if the GPU has finished performing the capture.

\begin{lstlisting}
while(!m_fiQueue.empty())
{
    const auto fiIdx = m_fiQueue.front();
    if(glClientWaitSync(m_fiFence[fiIdx], 0, 0) == GL_TIMEOUT_EXPIRED) break;
    glDeleteSync(m_fiFence[fiIdx]);
    glBindBuffer(GL_PIXEL_PACK_BUFFER, m_fiPbo[fiIdx]);
    auto ptr = glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, 320*180*4, GL_MAP_READ_BIT);
    FrameImage(ptr, 320, 180, m_fiQueue.size(), true);
    glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
    m_fiQueue.erase(m_fiQueue.begin());
}
\end{lstlisting}

Notice that in the call to \texttt{FrameImage} we are passing the remaining queue size as the \texttt{offset} parameter. Queue size represents how many frames ahead our program is relative to the GPU. Since we are sending past frame images, we need to specify how many frames behind the images are. Of course, if this would be synchronous capture (without the use of fences and with retrieval code after the capture setup), we would set \texttt{offset} to zero, as there would be no frame lag.

\subparagraph{High quality capture}

The code above uses \texttt{glBlitFramebuffer} function, which can only use nearest neighbor filtering. The use of such filtering can result in low-quality screenshots, as shown in figure~\ref{lowqualityss}. However, with a bit more work, it is possible to obtain nicer-looking screenshots, as presented in figure~\ref{highqualityss}. Unfortunately, you will need to set up a complete rendering pipeline for this to work.

First, you need to allocate an additional set of intermediate frame buffers and textures, sized the same as the screen. These new textures should have a minification filter set to \texttt{GL\_LINEAR\_MIPMAP\_LINEAR}. You will also need to set up everything needed to render a full-screen quad: a simple texturing shader and vertex buffer with appropriate data. Since you will use this vertex buffer to render to the scaled-down frame buffer, you may prepare its contents beforehand and update it only when the aspect ratio changes.

With all this done, you can perform the screen capture as follows:

\begin{itemize}
\item Setup vertex buffer configuration for the full-screen quad buffer (you only need position and uv~coordinates).
\item Blit the screen contents to the full-sized frame buffer.
\item Bind the texture backing the full-sized frame buffer.
\item Generate mipmaps using \texttt{glGenerateMipmap}.
\item Set viewport to represent the scaled-down image size.
\item Bind vertex buffer data, shader, setup the required uniforms.
\item Draw full-screen quad to the scaled-down frame buffer.
\item Retrieve frame buffer contents, as in the code above.
\item Restore viewport, vertex buffer configuration, bound textures, etc.
\end{itemize}

While this approach is much more complex than the previously discussed one, the resulting image quality increase makes it worthwhile.

\begin{figure}[h]
\centering
\begin{minipage}{0.45\textwidth}
\centering
\includegraphics[width=0.9\textwidth]{images/screenshot-lo.png}
\caption{Low-quality screen shot}
\label{lowqualityss}
\end{minipage}\hfill
\begin{minipage}{0.45\textwidth}
\centering
\includegraphics[width=0.9\textwidth]{images/screenshot-hi.png}
\caption{High-quality screen shot}
\label{highqualityss}
\end{minipage}
\end{figure}

You can see the performance results you may expect in a simple application in table~\ref{asynccapture}. The na\"ive capture performs synchronous retrieval of full-screen image and resizes it using \emph{stb\_image\_resize}. The proper and high-quality captures do things as described in this chapter.

\begin{table}[h]
\centering
\begin{tabular}[h]{c|c|c|c}
\textbf{Resolution} & \textbf{Na\"ive capture} & \textbf{Proper capture} & \textbf{High quality} \\ \hline
$1280\times720$ & 80~FPS & 4200~FPS & 2800~FPS \\
$2560\times1440$ & 23~FPS & 3300~FPS & 1600~FPS
\end{tabular}
\caption{Frame capture efficiency}
\label{asynccapture}
\end{table}

\subsection{Marking zones}
\label{markingzones}

To record a zone's\footnote{A \texttt{zone} represents the lifetime of a special on-stack profiler variable. Typically it would exist for the duration of a whole scope of the profiled function, but you also can measure time spent in scopes of a for-loop or an if-branch.} execution time add the \texttt{ZoneScoped} macro at the beginning of the scope you want to measure. This will automatically record function name, source file name, and location. Optionally you may use the \texttt{ZoneScopedC(color)} macro to set a custom color for the zone. Note that the color value will be constant in the recording (don't try to parametrize it). You may also set a custom name for the zone, using the \texttt{ZoneScopedN(name)} macro. Color and name may be combined by using the \texttt{ZoneScopedNC(name, color)} macro.

Use the \texttt{ZoneText(text, size)} macro to add a custom text string that the profiler will display along with the zone information (for example, name of the file you are opening). Multiple text strings can be attached to any single zone. The dynamic color of a zone can be specified with the \texttt{ZoneColor(uint32\_t)} macro to override the source location color. If you want to send a numeric value and don't want to pay the cost of converting it to a string, you may use the \texttt{ZoneValue(uint64\_t)} macro. Finally, you can check if the current zone is active with the \texttt{ZoneIsActive} macro.

If you want to set zone name on a per-call basis, you may do so using the \texttt{ZoneName(text, size)} macro. However, this name won't be used in the process of grouping the zones for statistical purposes (sections~\ref{statistics} and~\ref{findzone}).

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Important}
Zones are identified using static data structures embedded in program code. Therefore, you need to consider the lifetime of code in your application, as discussed in section~\ref{datalifetime}, to make sure that the profiler can access this data at any time during the program lifetime.

If you can't fulfill this requirement, you must use transient zones, described in section~\ref{transientzones}.
\end{bclogo}

\subsubsection{Manual management of zone scope}

The zone markup macros automatically report when they end, through the RAII mechanism\footnote{\url{https://en.cppreference.com/w/cpp/language/raii}}. This is very helpful, but sometimes you may want to mark the zone start and end points yourself, for example, if you want to have a zone that crosses the function's boundary. You can achieve this by using the C API, which is described in section~\ref{capi}.

\subsubsection{Multiple zones in one scope}
\label{multizone}

Using the \texttt{ZoneScoped} family of macros creates a stack variable named \texttt{\_\_\_tracy\_scoped\_zone}. If you want to measure more than one zone in the same scope, you will need to use the \texttt{ZoneNamed} macros, which require that you provide a name for the created variable. For example, instead of \texttt{ZoneScopedN("Zone name")}, you would use \texttt{ZoneNamedN(variableName, "Zone name", true)}\footnote{The last parameter is explained in section~\ref{filteringzones}.}.

The \texttt{ZoneText}, \texttt{ZoneColor}, \texttt{ZoneValue}, \texttt{ZoneIsActive}, and \texttt{ZoneName} macros apply to the zones created using the \texttt{ZoneScoped} macros. For zones created using the \texttt{ZoneNamed} macros, you can use the \texttt{ZoneTextV(variableName, text, size)}, \texttt{ZoneColorV(variableName, uint32\_t)}, \texttt{ZoneValueV(variableName, uint64\_t)}, \texttt{ZoneIsActiveV(variableName)}, or \texttt{ZoneNameV(variableName, text, size)} macros, or invoke the methods \texttt{Text}, \texttt{Color}, \texttt{Value}, \texttt{IsActive}, or \texttt{Name} directly on the variable you have created.

Zone objects can't be moved or copied.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcattention
]{Zone stack}
The \texttt{ZoneScoped} macros are imposing the creation and usage of an implicit zone stack. You must also follow the rules of this stack when using the named macros, which give you some more leeway in doing things. For example, you can only set the text for the zone which is on top of the stack, as you only could do with the \texttt{ZoneText} macro. It doesn't matter that you can call the \texttt{Text} method of a non-top zone which is accessible through a variable. Take a look at the following code:

\begin{lstlisting}
{
	ZoneNamed(Zone1, true);
	@\circled{a}@
	{
		ZoneNamed(Zone2, true);
		@\circled{b}@
	}
	@\circled{c}@
}
\end{lstlisting}

It is valid to set the \texttt{Zone1} text or name \emph{only} in places \circled{a} or \circled{c}. After \texttt{Zone2} is created at \circled{b} you can no longer perform operations on \texttt{Zone1}, until \texttt{Zone2} is destroyed.
\end{bclogo}

\subsubsection{Filtering zones}
\label{filteringzones}

Zone logging can be disabled on a per-zone basis by making use of the \texttt{ZoneNamed} macros. Each of the macros takes an \texttt{active} argument ('\texttt{true}' in the example in section~\ref{multizone}), which will determine whether the zone should be logged.

Note that this parameter may be a run-time variable, such as a user-controlled switch to enable profiling of a specific part of code only when required.

If the condition is constant at compile-time, the resulting code will not contain a branch (the profiling code will either be always enabled or won't be there at all). The following listing presents how you might implement profiling of specific application subsystems:

\begin{lstlisting}
enum SubSystems
{
	Sys_Physics		= 1 << 0,
	Sys_Rendering	= 1 << 1,
	Sys_NasalDemons	= 1 << 2
}

...

// Preferably a define in the build system
#define SUBSYSTEMS (Sys_Physics | Sys_NasalDemons)

...

void Physics::Process()
{
	ZoneNamed( __tracy, SUBSYSTEMS & Sys_Physics );		// always true, no runtime cost
	...
}

void Graphics::Render()
{
	ZoneNamed( __tracy, SUBSYSTEMS & Sys_Graphics );		// always false, no runtime cost
	...
}
\end{lstlisting}

\subsubsection{Transient zones}
\label{transientzones}

In order to prevent problems caused by unloadable code, described in section~\ref{datalifetime}, transient zones copy the source location data to an on-heap buffer. This way, the requirement on the string literal data being accessible for the rest of the program lifetime is relaxed, at the cost of increased memory usage.

Transient zones can be declared through the \texttt{ZoneTransient} and \texttt{ZoneTransientN} macros, with the same set of parameters as the \texttt{ZoneNamed} macros. See section~\ref{multizone} for details and make sure that you observe the requirements outlined there.

\subsubsection{Variable shadowing}

The following code is fully compliant with the C++ standard:

\begin{lstlisting}
void Function()
{
	ZoneScoped;
	...
	for(int i=0; i<10; i++)
	{
		ZoneScoped;
		...
	}
}
\end{lstlisting}

This doesn't stop some compilers from dispensing \emph{fashion advice} about variable shadowing (as both \texttt{ZoneScoped} calls create a variable with the same name, with the inner scope one shadowing the one in the outer scope). If you want to avoid these warnings, you will also need to use the \texttt{ZoneNamed} macros.

\subsubsection{Exiting program from within a zone}

Exiting the profiled application from inside a zone is not supported. When the client calls \texttt{exit()}, the profiler will wait for all zones to end before a program can be truly terminated. If program execution stops inside a zone, this will never happen, and the profiled application will seemingly hang up. At this point, you will need to manually terminate the program (or disconnect the profiler server).

As a workaround, you may add a \texttt{try}/\texttt{catch} pair at the bottom of the function stack (for example in the \texttt{main()} function) and replace \texttt{exit()} calls with throwing a custom exception. When this exception is caught, you may call \texttt{exit()}, knowing that the application's data structures (including profiling zones) were properly cleaned up.

\subsection{Marking locks}

Modern programs must use multi-threading to achieve the full performance capability of the CPU. However, correct execution requires claiming exclusive access to data shared between threads. When many threads want to simultaneously enter the same critical section, the application's multi-threaded performance advantage nullifies. To help solve this problem, Tracy can collect and display lock interactions in threads.

To mark a lock (mutex) for event reporting, use the \texttt{TracyLockable(type, varname)} macro. Note that the lock must implement the Mutex requirement\footnote{\url{https://en.cppreference.com/w/cpp/named_req/Mutex}} (i.e.,\ there's no support for timed mutexes). For a concrete example, you would replace the line

\begin{lstlisting}
std::mutex m_lock;
\end{lstlisting}

with

\begin{lstlisting}
TracyLockable(std::mutex, m_lock);
\end{lstlisting}

Alternatively, you may use \texttt{TracyLockableN(type, varname, description)} to provide a custom lock name at a global level, which will replace the automatically generated '\texttt{std::mutex m\_lock}'-like name. You may also set a custom name for a specific instance of a lock, through the \texttt{LockableName(varname, name, size)} macro.

The standard \texttt{std::lock\_guard} and \texttt{std::unique\_lock} wrappers should use the \texttt{LockableBase(type)} macro for their template parameter (unless you're using C++17, with improved template argument deduction). For example:

\begin{lstlisting}
std::lock_guard<LockableBase(std::mutex)> lock(m_lock);
\end{lstlisting}

To mark the location of a lock being held, use the \texttt{LockMark(varname)} macro after you have obtained the lock. Note that the \texttt{varname} must be a lock variable (a reference is also valid). This step is optional.

Similarly, you can use \texttt{TracySharedLockable}, \texttt{TracySharedLockableN} and \texttt{SharedLockableBase} to mark locks implementing the SharedMutex requirement\footnote{\url{https://en.cppreference.com/w/cpp/named_req/SharedMutex}}. Note that while there's no support for timed mutices in Tracy, both \texttt{std::shared\_mutex} and \texttt{std::shared\_timed\_mutex} may be used\footnote{Since \texttt{std::shared\_mutex} was added in C++17, using \texttt{std::shared\_timed\_mutex} is the only way to have shared mutex functionality in C++14.}.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bclampe
]{Condition variables}
The standard \texttt{std::condition\_variable} is only able to accept \texttt{std::mutex} locks. To be able to use Tracy lock wrapper, use \texttt{std::condition\_variable\_any} instead.
\end{bclogo}

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcattention
]{Caveats}
Due to the limits of internal bookkeeping in the profiler, you may use each lock in no more than 64 unique threads. If you have many short-lived temporary threads, consider using a thread pool to limit the number of created threads.
\end{bclogo}

\subsubsection{Custom locks}

If using the \texttt{TracyLockable} or \texttt{TracySharedLockable} wrappers does not fit your needs, you may want to add a more fine-grained instrumentation to your code. Classes \texttt{LockableCtx} and \texttt{SharedLockableCtx} contained in the \texttt{TracyLock.hpp} header contain all the required functionality. Lock implementations in classes \texttt{Lockable} and \texttt{SharedLockable} show how to properly perform context handling.

\subsection{Plotting data}
\label{plottingdata}

Tracy can capture and draw numeric value changes over time. You may use it to analyze draw call counts, number of performed queries, etc. To report data, use the \texttt{TracyPlot(name, value)} macro.

To configure how plot values are presented by the profiler, you may use the \texttt{TracyPlotConfig(name, format, step, fill, color)} macro, where \texttt{format} is one of the following options:

\begin{itemize}
\item \texttt{tracy::PlotFormatType::Number} -- values will be displayed as plain numbers.
\item \texttt{tracy::PlotFormatType::Memory} -- treats the values as memory sizes. Will display kilobytes, megabytes, etc.
\item \texttt{tracy::PlotFormatType::Percentage} -- values will be displayed as percentage (with value $100$ being equal to $100\%$).
\end{itemize}

The \texttt{step} parameter determines whether the plot will be displayed as a staircase or will smoothly change between plot points (see figure~\ref{plotconfig}). The \texttt{fill} parameter can be used to disable filling the area below the plot with a solid color.

\begin{figure}[h]
\centering\begin{tikzpicture}
[dot/.style={rectangle,draw,scale=0.5}];
\draw(0, -2) -- (1, -2.3) node[dot]{} -- (1.2, -3) node[dot]{} -- (1.8, -1.2) node[dot]{} -- (2.7, -0.5) node[dot]{} -- (3, -2) node[dot]{} -- (5, -2.5);
\draw(7, -1.5) -- (8, -1.5) -- (8, -2.3) node[dot]{} -- (8.2, -2.3) -- (8.2, -3) node[dot]{} -- (8.8, -3) -- (8.8, -1.2) node[dot]{} -- (9.7, -1.2) -- (9.7, -0.5) node[dot]{} -- (10, -0.5) -- (10, -2) node[dot]{} -- (12, -2);
\end{tikzpicture}
\caption{An identical set of values on a smooth plot (left) and a staircase plot (right).}
\label{plotconfig}
\end{figure}

Each plot has its own color, which by default is derived from the plot name (each unique plot name produces its own color, which does not change between profiling runs). If you want to provide your own color instead, you may enter the \texttt{color} parameter. Note that you should set the color value to \texttt{0} if you do not want to set your own color.

For reference, the following command sets the default parameters of the plot (that is, it's a no-op): \texttt{TracyPlotConfig(name, tracy::PlotFormatType::Number, false, true, 0)}.

It is beneficial but not required to use a unique pointer for name string literal (see section~\ref{uniquepointers} for more details).

\subsection{Message log}
\label{messagelog}

Fast navigation in large data sets and correlating zones with what was happening in the application may be difficult. To ease these issues, Tracy provides a message log functionality. You can send messages (for example, your typical debug output) using the \texttt{TracyMessage(text, size)} macro. Alternatively, use \texttt{TracyMessageL(text)} for string literal messages.

If you want to include color coding of the messages (for example to make critical messages easily visible), you can use \texttt{TracyMessageC(text, size, color)} or \texttt{TracyMessageLC(text, color)} macros.

\subsubsection{Application information}
\label{appinfo}

Tracy can collect additional information about the profiled application, which will be available in the trace description. This can include data such as the source repository revision, the application's environment (dev/prod), etc.

Use the \texttt{TracyAppInfo(text, size)} macro to report the data.

\subsection{Memory profiling}
\label{memoryprofiling}

Tracy can monitor the memory usage of your application. Knowledge about each performed memory allocation enables the following:

\begin{itemize}
\item Memory usage graph (like in massif, but fully interactive).
\item List of active allocations at program exit (memory leaks).
\item Visualization of the memory map.
\item Ability to rewind view of active allocations and memory map to any point of program execution.
\item Information about memory statistics of each zone.
\item Memory allocation hot-spot tree.
\end{itemize}

To mark memory events, use the \texttt{TracyAlloc(ptr, size)} and \texttt{TracyFree(ptr)} macros. Typically you would do that in overloads of \texttt{operator new} and \texttt{operator delete}, for example:

\begin{lstlisting}
void* operator new(std::size_t count)
{
    auto ptr = malloc(count);
    TracyAlloc(ptr, count);
    return ptr;
}

void operator delete(void* ptr) noexcept
{
    TracyFree(ptr);
    free(ptr);
}
\end{lstlisting}

In some rare cases (e.g., destruction of TLS block), events may be reported after the profiler is no longer available, which would lead to a crash. To work around this issue, you may use \texttt{TracySecureAlloc} and \texttt{TracySecureFree} variants of the macros.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Important}
Each tracked memory-free event must also have a corresponding memory allocation event. Tracy will terminate the profiling session if this assumption is broken (see section~\ref{instrumentationfailures}). If you encounter this issue, you may want to check for:

\begin{itemize}
\item Mismatched \texttt{malloc}/\texttt{new} or \texttt{free}/\texttt{delete}.
\item Reporting the same memory address being allocated twice (without a free between two allocations).
\item Double freeing the memory.
\item Untracked allocations made in external libraries that are freed in the application.
\item Places where the memory is allocated, but profiling markup is added.
\end{itemize}

This requirement is relaxed in the on-demand mode (section~\ref{ondemand}) because the memory allocation event might have happened before the server made the connection.
\end{bclogo}

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bclampe
]{Non-stable memory addresses}
Note that the pointer data you provide to the profiler does not have to reflect the actual memory layout, which you may not know in some cases. This includes the possibility of having multiple overlapping memory allocation regions. For example, you may want to track GPU memory, which may be mapped to different locations in the program address space during allocation and freeing. Or maybe you use some memory defragmentation scheme, which by its very design moves pointers around. You may instead use unique numeric identifiers to identify allocated objects in such cases. This will make some profiler facilities unavailable. For example, the memory map won't have much sense anymore.
\end{bclogo}

\subsubsection{Memory pools}
\label{memorypools}

Sometimes an application will use more than one memory pool. For example, in addition to tracking the \texttt{malloc}/\texttt{free} heap, you may also be interested in memory usage of a graphic API, such as Vulkan. Or maybe you want to see how your scripting language is managing memory.

To mark that a separate memory pool is to be tracked you should use the named version of memory macros, for example \texttt{TracyAllocN(ptr, size, name)} and \texttt{TracyFreeN(ptr, name)}, where \texttt{name} is an unique pointer to a string literal (section~\ref{uniquepointers}) identifying the memory pool.

\subsection{GPU profiling}
\label{gpuprofiling}

Tracy provides bindings for profiling OpenGL, Vulkan, Direct3D 11, Direct3D 12, and OpenCL execution time on GPU.

Note that the CPU and GPU timers may be unsynchronized unless you create a calibrated context, but the availability of calibrated contexts is limited. You can try to correct the desynchronization of uncalibrated contexts in the profiler's options (section~\ref{options}).

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bclampe
]{Check the scope}
If the graphic API you are using requires explicitly stating that you start and finish the recording of command buffers, remember that the instrumentation macros requirements must be satisfied during the zone's construction and destruction. For example, the zone destructor will be executed in the following code after buffer recording has ended, which is an error.

\begin{lstlisting}
{
    vkBeginCommandBuffer(cmd, &beginInfo);
    TracyVkZone(ctx, cmd, "Render");
    vkEndCommandBuffer(cmd);
}
\end{lstlisting}

Add a nested scope encompassing the command buffer recording section to fix such issues.
\end{bclogo}

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcattention
]{Caveat emptor}
The profiling results you will get can be unreliable or plainly wrong. It all depends on the quality of graphics drivers and how the underlying hardware implements timers. While Tracy employs some heuristics to make things as reliable as possible, it must talk to the GPU through the commonly unreliable API calls.

For example, on Linux, the Intel GPU driver will report 64-bit precision of time stamps. Unfortunately, this is not true, as the driver will only provide timestamps with 36-bit precision, rolling over the exceeding values. Tracy can detect such problems and employ workarounds. This is, sadly, not enough to make the readings reliable, as this timer we can access through the API is not a real one. Deep down, the driver has access to the actual timer, which it uses to provide the virtual values we can get. Unfortunately, this hardware timer has a period which \emph{does not match} the period of the API timer. As a result, the virtual timer will sometimes overflow \emph{in midst} of a cycle, making the reported time values jump forward. This is a problem that only the driver vendor can fix.

If you experience crippling problems while profiling the GPU, you might get better results with a different driver, different operating system, or different hardware.
\end{bclogo}

\subsubsection{OpenGL}

You will need to include the \texttt{public/tracy/TracyOpenGL.hpp} header file and declare each of your rendering contexts using the \texttt{TracyGpuContext} macro (typically, you will only have one context). Tracy expects no more than one context per thread and no context migration. To set a custom name for the context, use the \texttt{TracyGpuContextName(name, size)} macro.

To mark a GPU zone use the \texttt{TracyGpuZone(name)} macro, where \texttt{name} is a string literal name of the zone. Alternatively you may use \texttt{TracyGpuZoneC(name, color)} to specify zone color.

You also need to periodically collect the GPU events using the \texttt{TracyGpuCollect} macro. An excellent place to do it is after the swap buffers function call.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcattention
]{Caveats}
\begin{itemize}
\item OpenGL profiling is not supported on OSX, iOS\footnote{Because Apple is unable to implement standards properly.}.
\item Nvidia drivers are unable to provide consistent timing results when two OpenGL contexts are used simultaneously.
\item Calling the \texttt{TracyGpuCollect} macro is a fairly slow operation (couple \si{\micro\second}).
\end{itemize}
\end{bclogo}

\subsubsection{Vulkan}

Similarly, for Vulkan support you should include the \texttt{public/tracy/TracyVulkan.hpp} header file. Tracing Vulkan devices and queues is a bit more involved, and the Vulkan initialization macro \texttt{TracyVkContext(physdev, device, queue, cmdbuf)} returns an instance of \texttt{TracyVkCtx} object, which tracks an associated Vulkan queue. Cleanup is performed using the \texttt{TracyVkDestroy(ctx)} macro. You may create multiple Vulkan contexts. To set a custom name for the context, use the \texttt{TracyVkContextName(ctx, name, size)} macro.

The physical device, logical device, queue, and command buffer must relate to each other. The queue must support graphics or compute operations. The command buffer must be in the initial state and be able to be reset. The profiler will rerecord and submit it to the queue multiple times, and it will be in the executable state on exit from the initialization function.

To mark a GPU zone use the \texttt{TracyVkZone(ctx, cmdbuf, name)} macro, where \texttt{name} is a string literal name of the zone. Alternatively you may use \texttt{TracyVkZoneC(ctx, cmdbuf, name, color)} to specify zone color. The provided command buffer must be in the recording state, and it must be created within the queue that is associated with \texttt{ctx} context.

You also need to periodically collect the GPU events using the \texttt{TracyVkCollect(ctx, cmdbuf)} macro\footnote{It is considerably faster than the OpenGL's \texttt{TracyGpuCollect}.}. The provided command buffer must be in the recording state and outside a render pass instance.

\subparagraph{Calibrated context}

In order to maintain synchronization between CPU and GPU time domains, you will need to enable the \texttt{VK\_EXT\_calibrated\_timestamps} device extension and retrieve the following function pointers: \texttt{vkGetPhysicalDeviceCalibrateableTimeDomainsEXT} and \texttt{vkGetCalibratedTimestampsEXT}.

To enable calibrated context, replace the macro \texttt{TracyVkContext} with \texttt{TracyVkContextCalibrated} and pass the two functions as additional parameters, in the order specified above.

\subsubsection{Direct3D 11}

To enable Direct3D 11 support, include the \texttt{public/tracy/TracyD3D11.hpp} header file, and create a \texttt{TracyD3D11Ctx} object with the \texttt{TracyD3D11Context(device, devicecontext)} macro. The object should later be cleaned up with the \texttt{TracyD3D11Destroy} macro. Tracy does not support D3D11 command lists. To set a custom name for the context, use the \texttt{TracyGpuContextName(name, size)} macro.

To mark a GPU zone, use the \texttt{TracyD3D11Zone(name)} macro, where \texttt{name} is a string literal name of the zone. Alternatively you may use \texttt{TracyD3D11ZoneC(name, color)} to specify zone color.

You also need to periodically collect the GPU events using the \texttt{TracyD3D11Collect} macro. An excellent place to do it is after the swap chain present function.

\subsubsection{Direct3D 12}

To enable Direct3D 12 support, include the \texttt{public/tracy/TracyD3D12.hpp} header file. Tracing Direct3D 12 queues is nearly on par with the Vulkan implementation, where a \texttt{TracyD3D12Ctx} is returned from a call to \texttt{TracyD3D12Context(device, queue)}, which should be later cleaned up with the \texttt{TracyD3D12Destroy(ctx)} macro. Multiple contexts can be created, each with any queue type. To set a custom name for the context, use the \texttt{TracyD3D12ContextName(ctx, name, size)} macro.

The queue must have been created through the specified device, however, a command list is not needed for this stage.

Using GPU zones is the same as the Vulkan implementation, where the \texttt{TracyD3D12Zone(ctx, cmdList, name)} macro is used, with \texttt{name} as a string literal. \texttt{TracyD3D12ZoneC(ctx, cmdList, name, color)} can be used to create a custom-colored zone. The given command list must be in an open state.

The macro \texttt{TracyD3D12NewFrame(ctx)} is used to mark a new frame, and should appear before or after recording command lists, similar to \texttt{FrameMark}. This macro is a key component that enables automatic query data synchronization, so the user doesn't have to worry about synchronizing GPU execution before invoking a collection. Event data can then be collected and sent to the profiler using the \texttt{TracyD3D12Collect(ctx)} macro.

Note that GPU profiling may be slightly inaccurate due to artifacts from dynamic frequency scaling. To counter this, \texttt{ID3D12Device::SetStablePowerState()} can be used to enable accurate profiling, at the expense of some performance. If the machine is not in developer mode, the operating system will remove the device upon calling. Do not use this in the shipping code.

Direct3D 12 contexts are always calibrated.

\subsubsection{OpenCL}

OpenCL support is achieved by including the \texttt{public/tracy/TracyOpenCL.hpp} header file. Tracing OpenCL requires the creation of a Tracy OpenCL context using the macro \texttt{TracyCLContext(context, device)}, which will return an instance of \texttt{TracyCLCtx} object that must be used when creating zones. The specified \texttt{device} must be part of the \texttt{context}. Cleanup is performed using the \texttt{TracyCLDestroy(ctx)} macro. Although not common, it is possible to create multiple OpenCL contexts for the same application. To set a custom name for the context, use the \texttt{TracyCLContextName(ctx, name, size)} macro.

To mark an OpenCL zone one must make sure that a valid OpenCL \texttt{cl\_event} object is available. The event will be the object that Tracy will use to query profiling information from the OpenCL driver. For this to work, you must create all OpenCL queues with the \texttt{CL\_QUEUE\_PROFILING\_ENABLE} property.

OpenCL zones can be created with the \texttt{TracyCLZone(ctx, name)} where \texttt{name} will usually be a descriptive name for the operation represented by the \texttt{cl\_event}. Within the scope of the zone, you must call \texttt{TracyCLSetEvent(event)} for the event to be registered in Tracy.

Similar to Vulkan and OpenGL, you also need to periodically collect the OpenCL events using the \texttt{TracyCLCollect(ctx)} macro. An excellent place to perform this operation is after a \texttt{clFinish} since this will ensure that any previously queued OpenCL commands will have finished by this point.

\subsubsection{Multiple zones in one scope}

Putting more than one GPU zone macro in a single scope features the same issue as with the \texttt{ZoneScoped} macros, described in section~\ref{multizone} (but this time the variable name is \texttt{\_\_\_tracy\_gpu\_zone}).

To solve this problem, in case of OpenGL use the \texttt{TracyGpuNamedZone} macro in place of \texttt{TracyGpuZone} (or the color variant). The same applies to Vulkan and Direct3D 11/12 -- replace \texttt{TracyVkZone} with \texttt{TracyVkNamedZone} and \texttt{TracyD3D11Zone}/\texttt{TracyD3D12Zone} with \texttt{TracyD3D11NamedZone}/\texttt{TracyD3D12NamedZone}.

Remember to provide your name for the created stack variable as the first parameter to the macros.

\subsubsection{Transient GPU zones}

Transient zones (see section~\ref{transientzones} for details) are available in OpenGL, Vulkan, and Direct3D 11/12 macros.

\subsection{Fibers}
\label{fibers}

Fibers are lightweight threads, which are not under the operating system's control and need to be manually scheduled by the application. As far as Tracy is concerned, there are other cooperative multitasking primitives, like coroutines, or green threads, which also fall under this umbrella.

To enable fiber support in the client code, you will need to add the \texttt{TRACY\_FIBERS} define to your project. You need to do this explicitly, as there is a small performance hit due to additional processing.

To properly instrument fibers, you will need to modify the fiber dispatch code in your program. You will need to insert the \texttt{TracyFiberEnter(fiber)} macro every time a fiber starts or resumes execution. You will also need to insert the \texttt{TracyFiberLeave} macro when the execution control in a thread returns to the non-fiber part of the code. Note that you can safely call \texttt{TracyFiberEnter} multiple times in succession, without an intermediate \texttt{TracyFiberLeave} if one fiber is directly switching to another, without returning control to the fiber dispatch worker.

Fibers are identified by unique \texttt{const char*} string names. Remember that you should observe the rules laid out in section~\ref{uniquepointers} while handling such strings.

No additional instrumentation is needed in other parts of the code. Zones, messages, and other such events will be properly attributed to the currently running fiber in its own separate track.

A straightforward example, which is not actually using any OS fiber functionality, is presented below:

\begin{lstlisting}
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();
}
\end{lstlisting}

As you can see, there are two threads, \texttt{t1} and \texttt{t2}, which are simulating worker threads that a real fiber library would use. A C API zone is created in thread \texttt{t1} and is ended in thread \texttt{t2}. Without the fiber markup, this would be an invalid operation, but with fibers, the zone is attributed to fiber \texttt{job1}, and not to thread \texttt{t1} or \texttt{t2}.

\subsection{Collecting call stacks}
\label{collectingcallstacks}

Capture of true calls stacks can be performed by using macros with the \texttt{S} postfix, which require an additional parameter, specifying the depth of call stack to be captured. The greater the depth, the longer it will take to perform capture. Currently you can use the following macros: \texttt{ZoneScopedS}, \texttt{ZoneScopedNS}, \texttt{ZoneScopedCS}, \texttt{ZoneScopedNCS}, \texttt{TracyAllocS}, \texttt{TracyFreeS}, \texttt{TracySecureAllocS}, \texttt{TracySecureFreeS}, \texttt{TracyMessageS}, \texttt{TracyMessageLS}, \texttt{TracyMessageCS}, \texttt{TracyMessageLCS}, \texttt{TracyGpuZoneS}, \texttt{TracyGpuZoneCS}, \texttt{TracyVkZoneS}, \texttt{TracyVkZoneCS}, and the named and transient variants.

Be aware that call stack collection is a relatively slow operation. Table~\ref{CallstackTimes} and figure~\ref{CallstackPlot} show how long it took to perform a single capture of varying depth on multiple CPU architectures.

\begin{table}[h]
\centering
\begin{tabular}[h]{c|c|c|c|c}
\textbf{Depth} & \textbf{x86} & \textbf{x64} & \textbf{ARM} & \textbf{ARM64} \\ \hline
1 & 34 \si{\nano\second} & 98 \si{\nano\second} & 6.62 \si{\micro\second} & 6.63 \si{\micro\second} \\
2 & 35 \si{\nano\second} & 150 \si{\nano\second} & 8.08 \si{\micro\second} & 8.25 \si{\micro\second} \\
3 & 36 \si{\nano\second} & 168 \si{\nano\second} & 9.75 \si{\micro\second} & 10 \si{\micro\second} \\
4 & 39 \si{\nano\second} & 190 \si{\nano\second} & 10.92 \si{\micro\second} & 11.58 \si{\micro\second} \\
5 & 42 \si{\nano\second} & 206 \si{\nano\second} & 12.5 \si{\micro\second} & 13.33 \si{\micro\second} \\
10 & 52 \si{\nano\second} & 306 \si{\nano\second} & 19.62 \si{\micro\second} & 21.71 \si{\micro\second} \\
15 & 63 \si{\nano\second} & 415 \si{\nano\second} & 26.83 \si{\micro\second} & 30.13 \si{\micro\second} \\
20 & 77 \si{\nano\second} & 531 \si{\nano\second} & 34.25 \si{\micro\second} & 38.71 \si{\micro\second} \\
25 & 89 \si{\nano\second} & 630 \si{\nano\second} & 41.17 \si{\micro\second} & 47.17 \si{\micro\second} \\
30 & 109 \si{\nano\second} & 735 \si{\nano\second} & 48.33 \si{\micro\second} & 55.63 \si{\micro\second} \\
35 & 123 \si{\nano\second} & 843 \si{\nano\second} & 55.87 \si{\micro\second} & 64.09 \si{\micro\second} \\
40 & 142 \si{\nano\second} & 950 \si{\nano\second} & 63.12 \si{\micro\second} & 72.59 \si{\micro\second} \\
45 & 154 \si{\nano\second} & 1.05 \si{\micro\second} & 70.54 \si{\micro\second} & 81 \si{\micro\second} \\
50 & 167 \si{\nano\second} & 1.16 \si{\micro\second} & 78 \si{\micro\second} & 89.5 \si{\micro\second} \\
55 & 179 \si{\nano\second} & 1.26 \si{\micro\second} & 85.04 \si{\micro\second} & 98 \si{\micro\second} \\
60 & 193 \si{\nano\second} & 1.37 \si{\micro\second} & 92.75 \si{\micro\second} & 106.59 \si{\micro\second}
\end{tabular}
\caption{Median times of zone capture with call stack. x86, x64: i7 8700K; ARM: Banana Pi; ARM64: ODROID-C2. Selected architectures are plotted on figure~\ref{CallstackPlot}}
\label{CallstackTimes}
\end{table}

\begin{figure}[h]
\centering\begin{tikzpicture}
\begin{axis}[xlabel=Call stack depth,ylabel=Time (\si{\nano\second}), legend pos=north west]
\addplot[smooth, mark=o, red] plot coordinates {
(1, 98) (2, 150) (3, 168) (4, 190) (5, 206) (10, 306) (15, 415) (20, 531) (25, 630) (30, 735) (35, 843) (40, 950) (45, 1050) (50, 1160) (55, 1260) (60, 1370)
};
\addlegendentry{x64}
\addplot[smooth, mark=x, blue] plot coordinates {
(1, 34) (2, 35) (3, 36) (4, 39) (5, 42) (10, 52) (15, 63) (20, 77) (25, 89) (30, 109) (35, 123) (40, 142) (45, 154) (50, 167) (55, 179) (60, 193)
};
\addlegendentry{x86}
\end{axis}
\end{tikzpicture}
\caption{Plot of call stack capture times (see table~\ref{CallstackTimes}). Notice that the capture time grows linearly with requested capture depth}
\label{CallstackPlot}
\end{figure}

You can force call stack capture in the non-\texttt{S} postfixed macros by adding the \texttt{TRACY\_CALLSTACK} define, set to the desired call stack capture depth. This setting doesn't affect the explicit call stack macros.

The maximum call stack depth that the profiler can retrieve is 62 frames. This is a restriction at the level of the operating system.

Tracy will automatically exclude certain uninteresting functions from the captured call stacks. So, for example, the pass-through intrinsic wrapper functions won't be reported.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Important!}
Collecting call stack data will also trigger retrieval of profiled program's executable code by the profiler. See section~\ref{executableretrieval} for details.
\end{bclogo}

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bclampe
]{How to disable}
Tracy will prepare for call stack collection regardless of whether you use the functionality or not. In some cases, this may be unwanted or otherwise troublesome for the user. To disable support for collecting call stacks, define the \texttt{TRACY\_NO\_CALLSTACK} macro.
\end{bclogo}

\subsubsection{Debugging symbols}

You must compile the profiled application with debugging symbols enabled to have correct call stack information. You can achieve that in the following way:

\begin{itemize}
\item On MSVC, open the project properties and go to \menu[,]{Linker,Debugging,Generate Debug Info}, where you should select the \emph{Generate Debug Information} option.
\item On gcc or clang remember to specify the debugging information \texttt{-g} parameter during compilation and \emph{do not} add the strip symbols \texttt{-s} parameter. Additionally, omitting frame pointers will severely reduce the quality of stack traces, which can be fixed by adding the \texttt{-fno-omit-frame-pointer} parameter. Link the executable with an additional option \texttt{-rdynamic} (or \texttt{-{}-export-dynamic}, if you are passing parameters directly to the linker).
\item On OSX, you may need to run \texttt{dsymutil} to extract the debugging data out of the executable binary.
\item On iOS you will have to add a \emph{New Run Script Phase} to your XCode project, which shall execute the following shell script:

\begin{lstlisting}[language=sh]
cp -rf ${TARGET_BUILD_DIR}/${WRAPPER_NAME}.dSYM/* ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/${PRODUCT_NAME}.dSYM
\end{lstlisting}

You will also need to setup proper dependencies, by setting the following input file:\\
\texttt{\$\{TARGET\_BUILD\_DIR\}/\$\{WRAPPER\_NAME\}.dSYM}, and the following output file:\\
\texttt{\$\{TARGET\_BUILD\_DIR\}/\$\{UNLOCALIZED\_RESOURCES\_FOLDER\_PATH\}/\$\{PRODUCT\_NAME\}.dSYM}.
\end{itemize}

\paragraph{External libraries}

You may also be interested in symbols from external libraries, especially if you have sampling profiling enabled (section~\ref{sampling}).

\subparagraph{Windows}

In MSVC you can retrieve such symbols by going to \menu[,]{Tools,Options,Debugging,Symbols} and selecting appropriate \emph{Symbol file (.pdb) location} servers. Note that additional symbols may significantly increase application startup times.

Libraries built with vcpkg typically provide PDB symbol files, even for release builds. Using vcpkg to obtain libraries has the extra benefit that everything is built using local source files, which allows Tracy to provide a source view not only of your application but also the libraries you use.

\subparagraph{Unix}

On Linux\footnote{And possibly other systems, if they decide to adapt the required tooling.} information needed for debugging traditionally has been provided by special packages named \texttt{debuginfo}, \texttt{dbgsym}, or similar. You can use them to retrieve symbols, but keep in mind the following:

\begin{enumerate}
\item Your distribution has to provide such packages. Not each one does.
\item Debug packages are usually stored in a separate repository, which you must manually enable.
\item You need to install a separate package for each library you want to have symbols for.
\item Debugging information can require large amounts of disk space.
\end{enumerate}

A modern alternative to installing static debug packages is to use the \emph{debuginfod} system, which performs on-demand delivery of debugging information across the internet. See \url{https://sourceware.org/elfutils/Debuginfod.html} for more details. Since this new method of symbol delivery is not yet universally supported, you will have to manually enable it, both in your system and in Tracy.

First, make sure your distribution maintains a debuginfod server. Then, install the \texttt{debuginfod} library. You also need to ensure you have appropriately configured which server to access, but distribution maintainers usually provide this. Next, add the \texttt{TRACY\_DEBUGINFOD} define to the program you want to profile and link it with \texttt{libdebuginfod}. This will enable network delivery of symbols and source file contents. However, the first run (including after a system update) may be slow to respond until the local debuginfod cache becomes filled.

\paragraph{Using the dbghelp library on Windows}

While Tracy will try to expand the known symbols list when it encounters a new module for the first time, you may want to be able to do such a thing manually. Or maybe you are using the \texttt{dbghelp.dll} library in some other way in your project, for example, to present a call stack to the user at some point during execution.

Since dbghelp functions are not thread-safe, you must take extra steps to make sure your calls to the \texttt{Sym*} family of functions are not colliding with calls made by Tracy. To do so, perform the following steps:

\begin{enumerate}
\item Add a \texttt{TRACY\_DBGHELP\_LOCK} define, with the value set to prefix of lock-handling functions (for example: \texttt{TRACY\_DBGHELP\_LOCK=DbgHelp}).
\item Create a dbghelp lock (i.e., mutex) in your application.
\item Provide a set of \texttt{Init}, \texttt{Lock} and \texttt{Unlock} functions, including the provided prefix name, which will operate on the lock. These functions must be defined using the C linkage. Notice that there's no cleanup function.
\item Remember to protect access to dbghelp in your code appropriately!
\end{enumerate}

An example implementation of such a lock interface is provided below, as a reference:

\begin{lstlisting}
extern "C"
{
static HANDLE dbgHelpLock;

void DbgHelpInit() { dbgHelpLock = CreateMutex(nullptr, FALSE, nullptr); }
void DbgHelpLock() { WaitForSingleObject(dbgHelpLock, INFINITE); }
void DbgHelpUnlock() { ReleaseMutex(dbgHelpLock); }
}
\end{lstlisting}

\paragraph{Disabling resolution of inline frames}

Inline frames retrieval on Windows can be multiple orders of magnitude slower than just performing essential symbol resolution. This manifests as profiler seemingly being stuck for a long time, having hundreds of thousands of query backlog entries queued, which are slowly trickling down. If your use case requires speed of operation rather than having call stacks with inline frames included, you may define the \texttt{TRACY\_NO\_CALLSTACK\_INLINES} macro, which will make the profiler stick to the basic but fast frame resolution mode.

\subsection{Lua support}

To profile Lua code using Tracy, include the \texttt{public/tracy/TracyLua.hpp} header file in your Lua wrapper and execute \texttt{tracy::LuaRegister(lua\_State*)} function to add instrumentation support.

In the Lua code, add \texttt{tracy.ZoneBegin()} and \texttt{tracy.ZoneEnd()} calls to mark execution zones. You need to call the \texttt{ZoneEnd} method because there is no automatic destruction of variables in Lua, and we don't know when the garbage collection will be performed. \emph{Double check if you have included all return paths!}

Use \texttt{tracy.ZoneBeginN(name)} if you want to set a custom zone name\footnote{While technically this name doesn't need to be constant, like in the \texttt{ZoneScopedN} macro, it should be, as it is used to group the zones. This grouping is then used to display various statistics in the profiler. You may still set the per-call name using the \texttt{tracy.ZoneName} method.}.

Use \texttt{tracy.ZoneText(text)} to set zone text.

Use \texttt{tracy.Message(text)} to send messages.

Use \texttt{tracy.ZoneName(text)} to set zone name on a per-call basis.

Lua instrumentation needs to perform additional work (including memory allocation) to store source location. This approximately doubles the data collection cost.

\subsubsection{Call stacks}

To collect Lua call stacks (see section~\ref{collectingcallstacks}), replace \texttt{tracy.ZoneBegin()} calls with \texttt{tracy.ZoneBeginS(depth)}, and \texttt{tracy.ZoneBeginN(name)} calls with \texttt{tracy.ZoneBeginNS(name, depth)}. Using the \texttt{TRACY\_CALLSTACK} macro automatically enables call stack collection in all zones.

Be aware that for Lua call stack retrieval to work, you need to be on a platform that supports the collection of native call stacks.

Cost of performing Lua call stack capture is presented in table~\ref{CallstackTimesLua} and figure~\ref{CallstackPlotLua}. Lua call stacks include native call stacks, which have a capture cost of their own (table~\ref{CallstackTimes}), and the \texttt{depth} parameter is applied for both captures. The presented data were captured with full Lua stack depth, but only 13 frames were available on the native call stack. Hence, to explain the non-linearity of the graph, you need to consider what was truly measured:

\begin{displaymath}
\text{Cost}_{\text{total}}(\text{depth}) =
\begin{cases}
\text{Cost}_{\text{Lua}}(\text{depth}) + \text{Cost}_{\text{native}}(\text{depth}) & \text{when depth} \leq 13 \\
\text{Cost}_{\text{Lua}}(\text{depth}) + \text{Cost}_{\text{native}}(13) & \text{when depth} > 13
\end{cases}
\end{displaymath}

\begin{table}[h]
\centering
\begin{tabular}[h]{c|c}
\textbf{Depth} & \textbf{Time} \\ \hline
1 & 707 \si{\nano\second} \\
2 & 699 \si{\nano\second} \\
3 & 624 \si{\nano\second} \\
4 & 727 \si{\nano\second} \\
5 & 836 \si{\nano\second} \\
10 & 1.77 \si{\micro\second} \\
15 & 2.44 \si{\micro\second} \\
20 & 2.51 \si{\micro\second} \\
25 & 2.98 \si{\micro\second} \\
30 & 3.6 \si{\micro\second} \\
35 & 4.33 \si{\micro\second} \\
40 & 5.17 \si{\micro\second} \\
45 & 6.01 \si{\micro\second} \\
50 & 6.99 \si{\micro\second} \\
55 & 8.11 \si{\micro\second} \\
60 & 9.17 \si{\micro\second}
\end{tabular}
\caption{Median times of Lua zone capture with call stack (x64, 13 native frames)}
\label{CallstackTimesLua}
\end{table}

\begin{figure}[h]
\centering\begin{tikzpicture}
\begin{axis}[xlabel=Call stack depth,ylabel=Time (\si{\micro\second}), legend pos=north west]
\addplot[smooth, mark=o, red] plot coordinates {
(1, 0.707) (2, 0.699) (3, 0.624) (4, 0.727) (5, 0.836) (10, 1.770) (15, 2.440) (20, 2.510) (25, 2.980) (30, 3.600) (35, 4.330) (40, 5.170) (45, 6.010) (50, 6.990) (55, 8.110) (60, 9.170)
};
\end{axis}
\end{tikzpicture}
\caption{Plot of call Lua stack capture times (see table~\ref{CallstackTimesLua})}
\label{CallstackPlotLua}
\end{figure}

\subsubsection{Instrumentation cleanup}

Even if Tracy is disabled, you still have to pay the no-op function call cost. To prevent that, you may want to use the \texttt{tracy::LuaRemove(char* script)} function, which will replace instrumentation calls with white-space. This function does nothing if the profiler is enabled.

\subsection{C API}
\label{capi}

To profile code written in C programming language, you will need to include the \texttt{public/tracy/TracyC.h} header file, which exposes the C API.

At the moment, there's no support for C API based markup of locks, GPU zones, or Lua.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Important}
Tracy is written in C++, so you will need to have a C++ compiler and link with C++ standard library, even if your program is strictly pure C.
\end{bclogo}

\subsubsection{Setting thread names}

To set thread names (section~\ref{namingthreads}) using the C API you should use the \texttt{TracyCSetThreadName(name)} macro.

\subsubsection{Frame markup}

To mark frames, as described in section~\ref{markingframes}, use the following macros:

\begin{itemize}
\item \texttt{TracyCFrameMark}
\item \texttt{TracyCFrameMarkNamed(name)}
\item \texttt{TracyCFrameMarkStart(name)}
\item \texttt{TracyCFrameMarkEnd(name)}
\item \texttt{TracyCFrameImage(image, width, height, offset, flip)}
\end{itemize}

\subsubsection{Zone markup}
\label{czonemarkup}

The following macros mark the beginning of a zone:

\begin{itemize}
\item \texttt{TracyCZone(ctx, active)}
\item \texttt{TracyCZoneN(ctx, name, active)}
\item \texttt{TracyCZoneC(ctx, color, active)}
\item \texttt{TracyCZoneNC(ctx, name, color, active)}
\end{itemize}

Refer to sections~\ref{markingzones} and~\ref{multizone} for description of macro variants and parameters. The \texttt{ctx} parameter specifies the name of a data structure, which the macro will create on the stack to hold the internal zone data.

Unlike C++, there's no automatic destruction mechanism in C, so you will need to mark where the zone ends manually. To do so use the \texttt{TracyCZoneEnd(ctx)} macro.

Zone text and name may be set by using the \texttt{TracyCZoneText(ctx, txt, size)}, \texttt{TracyCZoneValue(ctx, value)} and \texttt{TracyCZoneName(ctx, txt, size)} macros. Make sure you are following the zone stack rules, as described in section~\ref{multizone}!

\paragraph{Zone context data structure}
\label{zonectx}

In typical use cases the zone context data structure is hidden from your view, requiring only to specify its name for the \texttt{TracyCZone} and \texttt{TracyCZoneEnd} macros. However, it is possible to use it in advanced scenarios, for example, if you want to start a zone in one function, then end it in another one. To do so, you will need to forward the data structure either through a function parameter or as a return value or place it in a thread-local stack structure. To accomplish this, you need to keep in mind the following rules:

\begin{itemize}
\item The created variable name is exactly what you pass as the \texttt{ctx} parameter.
\item The data structure is of an opaque, immutable type \texttt{TracyCZoneCtx}.
\item Contents of the data structure can be copied by assignment. Do not retrieve or use the structure's address -- this is asking for trouble.
\item You \emph{must} use the data structure (or any of its copies) exactly \emph{once} to end a zone.
\item Zone \emph{must} end in the same thread in which it was started.
\end{itemize}

\paragraph{Zone validation}

Since all C API instrumentation has to be done by hand, it is possible to miss some code paths where a zone should be started or ended. Tracy will perform additional validation of instrumentation correctness to prevent bad profiling runs. Read section~\ref{instrumentationfailures} for more information.

However, the validation comes with a performance cost, which you may not want to pay. Therefore, if you are \emph{entirely sure} that the instrumentation is not broken in any way, you may use the \texttt{TRACY\_NO\_VERIFY} macro, which will disable the validation code.

\paragraph{Transient zones in C API}

There is no explicit support for transient zones (section~\ref{transientzones}) in the C API macros. However, this functionality can be implemented by following instructions outlined in section~\ref{capibindings}.

\subsubsection{Memory profiling}

Use the following macros in your implementations of \texttt{malloc} and \texttt{free}:

\begin{itemize}
\item \texttt{TracyCAlloc(ptr, size)}
\item \texttt{TracyCFree(ptr)}
\item \texttt{TracyCSecureAlloc(ptr, size)}
\item \texttt{TracyCSecureFree(ptr)}
\end{itemize}

Correctly using this functionality can be pretty tricky. You also will need to handle all the memory allocations made by external libraries (which typically allow usage of custom memory allocation functions) and the allocations made by system functions. If you can't track such an allocation, you will need to make sure freeing is not reported\footnote{It's not uncommon to see a pattern where a system function returns some allocated memory, which you then need to release.}.

There is no explicit support for \texttt{realloc} function. You will need to handle it by marking memory allocations and frees, according to the system manual describing the behavior of this routine.

Memory pools (section~\ref{memorypools}) are supported through macros with \texttt{N} postfix.

For more information about memory profiling, refer to section~\ref{memoryprofiling}.

\subsubsection{Plots and messages}

To send additional markup in form of plot data points or messages use the following macros:

\begin{itemize}
\item \texttt{TracyCPlot(name, val)}
\item \texttt{TracyCPlotF(name, val)}
\item \texttt{TracyCPlotI(name, val)}
\item \texttt{TracyCMessage(txt, size)}
\item \texttt{TracyCMessageL(txt)}
\item \texttt{TracyCMessageC(txt, size, color)}
\item \texttt{TracyCMessageLC(txt, color)}
\item \texttt{TracyCAppInfo(txt, size)}
\end{itemize}

Consult sections~\ref{plottingdata} and~\ref{messagelog} for more information.

\subsubsection{GPU zones}

Hooking up support for GPU zones requires a bit more work than usual. The C API provides a low-level interface that you can use to submit the data, but there are no facilities to help you with timestamp processing.

Moreover, there are two sets of functions described below. The standard set sends data asynchronously, while the \texttt{\_serial} one ensures proper ordering of all events, regardless of the originating thread. Generally speaking, you should be using the asynchronous functions only in the case of strictly single-threaded APIs, like OpenGL.

A GPU context can be created with the \texttt{\_\_\_tracy\_emit\_gpu\_new\_context} function (or the serialized variant). You'll need to specify:

\begin{itemize}
\item \texttt{context} -- a unique context id.
\item \texttt{gpuTime} -- an initial GPU timestamp.
\item \texttt{period} -- the timestamp period of the GPU.
\item \texttt{flags} -- the flags to use.
\item \texttt{type} -- the GPU context type.
\end{itemize}

GPU contexts can be named using the \texttt{\_\_\_tracy\_emit\_gpu\_context\_name} function.

GPU zones can be created with the \texttt{\_\_\_tracy\_emit\_gpu\_zone\_begin\_alloc} function. The \texttt{srcloc} parameter is the address of the source location data allocated via \texttt{\_\_\_tracy\_alloc\_srcloc} or \texttt{\_\_\_tracy\_alloc\_srcloc\_name}. The \texttt{queryId} parameter is the id of the corresponding timestamp query. It should be unique on a per-frame basis.

GPU zones are ended via \texttt{\_\_\_tracy\_emit\_gpu\_zone\_end}.

When the timestamps are fetched from the GPU, they must then be emitted via the \texttt{\_\_\_tracy\_emit\_gpu\_time} function. After all timestamps for a frame are emitted, \texttt{queryIds} may be re-used.

To see how you should use this API, you should look at the reference implementation contained in API-specific C++ headers provided by Tracy. For example, to see how to write your instrumentation of OpenGL, you should closely follow the contents of the \texttt{TracyOpenGL.hpp} implementation.

\subsubsection{Fibers}

Fibers are available in the C API through the \texttt{TracyCFiberEnter} and \texttt{TracyCFiberLeave} macros. To use them, you should observe the requirements listed in section~\ref{fibers}.

\subsubsection{Connection Status}

To query the connection status (section~\ref{connectionstatus}) using the C API you should use the \texttt{TracyCIsConnected} macro.

\subsubsection{Call stacks}

You can collect call stacks of zones and memory allocation events, as described in section~\ref{collectingcallstacks}, by using macros with \texttt{S} postfix, such as: \texttt{TracyCZoneS}, \texttt{TracyCZoneNS}, \texttt{TracyCZoneCS}, \texttt{TracyCZoneNCS}, \texttt{TracyCAllocS}, \texttt{TracyCFreeS}, and so on.

\subsubsection{Using the C API to implement bindings}
\label{capibindings}

Tracy C API exposes functions with the \texttt{\_\_\_tracy} prefix that you may use to write bindings to other programming languages. Most of the functions available are a counterpart to macros described in section~\ref{capi}. However, some functions do not have macro equivalents and are dedicated expressly for binding implementation purposes. This includes the following:

\begin{itemize}
\item \texttt{\_\_\_tracy\_startup\_profiler(void)}
\item \texttt{\_\_\_tracy\_shutdown\_profiler(void)}
\item \texttt{\_\_\_tracy\_alloc\_srcloc(uint32\_t line, const char* source, size\_t sourceSz, const char* function, size\_t functionSz)}
\item \texttt{\_\_\_tracy\_alloc\_srcloc\_name(uint32\_t line, const char* source, size\_t sourceSz, const char* function, size\_t functionSz, const char* name, size\_t nameSz)}
\end{itemize}

Here \texttt{line} is line number in the \texttt{source} source file and \texttt{function} is the
name of a function in which the zone is created. \texttt{sourceSz} and \texttt{functionSz} are the
size of the corresponding string arguments in bytes. You may additionally specify an optional zone
name, by providing it in the \texttt{name} variable, and specifying its size in \texttt{nameSz}.

The \texttt{\_\_\_tracy\_alloc\_srcloc} and \texttt{\_\_\_tracy\_alloc\_srcloc\_name} functions
return an \texttt{uint64\_t} source location identifier corresponding to an \emph{allocated source
location}. As these functions do not require the provided string data to be available after they
return, the calling code is free to deallocate them at any time afterward. This way, the string
lifetime requirements described in section~\ref{textstrings} are relaxed.

The \texttt{uint64\_t} return value from allocation functions must be passed to one of the zone
begin functions:

\begin{itemize}
\item \texttt{\_\_\_tracy\_emit\_zone\_begin\_alloc(srcloc, active)}
\item \texttt{\_\_\_tracy\_emit\_zone\_begin\_alloc\_callstack(srcloc, depth, active)}
\end{itemize}


These functions return a \texttt{TracyCZoneCtx} context value, which must be handled, as described
in sections~\ref{czonemarkup} and~\ref{zonectx}.

The variable representing an allocated source location is of an opaque type. After it is passed to one of the zone begin functions, its value \emph{cannot be reused} (the variable is consumed). You must allocate a new source location for each zone begin event, even if the location data would be the same as in the previous instance.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Important}
Since you are directly calling the profiler functions here, you will need to take care of manually
disabling the code if the \texttt{TRACY\_ENABLE} macro is not defined.
\end{bclogo}

\subsection{Automated data collection}
\label{automated}

Tracy will perform an automatic collection of system data without user intervention. This behavior is platform-specific and may not be available everywhere. Refer to section~\ref{featurematrix} for more information.

\subsubsection{Privilege elevation}
\label{privilegeelevation}

Some profiling data can only be retrieved using the kernel facilities, which are not available to users with normal privilege level. To collect such data, you will need to elevate your rights to the administrator level. You can do so either by running the profiled program from the \texttt{root} account on Unix or through the \emph{Run as administrator} option on Windows\footnote{To make this easier, you can run MSVC with admin privileges, which will be inherited by your program when you start it from within the IDE.}. On Android, you will need to have a rooted device (see section~\ref{androidlunacy} for additional information).

As this system-level tracing functionality is part of the automated collection process, no user intervention is necessary to enable it (assuming that the program was granted the rights needed). However, if, for some reason, you would want to prevent your application from trying to access kernel data, you may recompile your program with the \texttt{TRACY\_NO\_SYSTEM\_TRACING} define.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bclampe
]{What should be granted privileges?}
Sometimes it may be confusing which program should be given admin access. After all, some other profilers have to run elevated to access all their capabilities.

In the case of Tracy, you should give the administrative rights to \emph{the profiled application}. Remember that the server part of the profiler (where the data is collected and displayed) may be running on another machine, and thus you can't use it to access kernel data.
\end{bclogo}

\subsubsection{CPU usage}

System-wide CPU load is gathered with relatively high granularity (one reading every 100 \si{\milli\second}). The readings are available as a plot (see section~\ref{plots}). Note that this parameter considers all applications running on the system, not only the profiled program.

\subsubsection{Context switches}
\label{contextswitches}

Since the profiled program is executing simultaneously with other applications, you can't have exclusive access to the CPU. Instead, the multitasking operating system's scheduler gives threads waiting to execute short time slices to do part of their work. Afterward, threads are preempted to give other threads a chance to run. This ensures that each program running in the system has a fair environment, and no program can hog the system resources for itself.

As a corollary, it is often not enough to know how long it took to execute a zone. For example, the thread in which a zone was running might have been suspended by the system. This would have artificially increased the time readings.

To solve this problem, Tracy collects context switch\footnote{A context switch happens when any given CPU core stops executing one thread and starts running another one.} information. This data can then be used to see when a zone was in the executing state and where it was waiting to be resumed.

You may disable context switch data capture by adding the \texttt{TRACY\_NO\_CONTEXT\_SWITCH} define to the client. Since with this feature you are observing other programs, you can only use it after privilege elevation, which is described in section~\ref{privilegeelevation}.

\subsubsection{CPU topology}
\label{cputopology}

Tracy may discover CPU topology data to provide further information about program performance characteristics. It is handy when combined with context switch information (section~\ref{contextswitches}).

In essence, the topology information gives you context about what any given \emph{logical CPU} really is and how it relates to other logical CPUs. The topology hierarchy consists of packages, cores, and threads.

Packages contain cores and shared resources, such as memory controller, L3 cache, etc. A store-bought CPU is an example of a package. While you may think that multi-package configurations would be a domain of servers, they are actually quite common in the mobile devices world, with many platforms using the \emph{big.LITTLE} arrangement of two packages in one silicon chip.

Cores contain at least one thread and shared resources: execution units, L1 and L2 cache, etc.

Threads (or \emph{logical CPUs}; not to be confused with program threads) are basically the processor instruction pipelines. A pipeline might become stalled, for example, due to pending memory access, leaving core resources unused. To reduce this bottleneck, some CPUs may use simultaneous multithreading\footnote{Commonly known as Hyper-threading.}, in which more than one pipeline will be using a single physical core resources.

Knowing which package and core any logical CPU belongs to enables many insights. For example, two threads scheduled to run on the same core will compete for shared execution units and cache, resulting in reduced performance. Or, migrating a program thread from one core to another will invalidate the L1 and L2 cache. However, such invalidation is less costly than migration from one package to another, which also invalidates the L3 cache.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Important}
In this manual, the word \emph{core} is typically used as a short term for \emph{logical CPU}. Please do not confuse it with physical processor cores.
\end{bclogo}

\subsubsection{Call stack sampling}
\label{sampling}

Manual markup of zones doesn't cover every function existing in a program and cannot be performed in system libraries or the kernel. This can leave blank spaces on the trace, leaving you no clue what the application was doing. However, Tracy can periodically inspect the state of running threads, providing you with a snapshot of the call stack at the time when sampling was performed. While this information doesn't have the fidelity of manually inserted zones, it can sometimes give you an insight into where to go next.

This feature requires privilege elevation on Windows, but not on Linux. However, running as root on Linux will also provide you the kernel stack traces. Additionally, you should review chapter~\ref{collectingcallstacks} to see if you have proper setup for the required program debugging data.

By default, sampling is performed at 8 kHz frequency on Windows (the maximum possible value). On Linux and Android, it is performed at 10 kHz\footnote{The maximum sampling frequency is limited by the \texttt{kernel.perf\_event\_max\_sample\_rate} sysctl parameter.}. You can change this value by providing the sampling frequency (in Hz) through the \texttt{TRACY\_SAMPLING\_HZ} macro.

Call stack sampling may be disabled by using the \texttt{TRACY\_NO\_SAMPLING} define.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Linux sampling rate limits}
The operating system may decide that sampling takes too much CPU time and reduce the allowed sampling rate. This can be seen in \texttt{dmesg} output as:

\texttt{perf: interrupt took too long, lowering kernel.perf\_event\_max\_sample\_rate to \emph{value}}.

If the \emph{value} goes below the sample rate Tracy wants to use, sampling will be silently disabled. To make it work again, you can set an appropriate value in the \texttt{kernel.perf\_event\_max\_sample\_rate} kernel parameter, using the \texttt{sysctl} utility.

Should you want to disable this mechanism, you can set the \texttt{kernel.perf\_cpu\_time\_max\_percent} parameter to zero. Be sure to read what this would do, as it may have serious consequences that you should be aware of.
\end{bclogo}

\paragraph{Wait stacks}
\label{waitstacks}

The sampling functionality also captures call stacks for context switch events. Such call stacks will show you what the application was doing when the thread was suspended and subsequently resumed, hence the name. We can categorize wait stacks into the following categories:

\begin{enumerate}
\item Random preemptive multitasking events, which are expected and do not have any significance.
\item Expected waits, which may be caused by issuing sleep commands, waiting for a lock to become available, performing I/O, and so on. Quantitative analysis of such events may (but probably won't) direct you to some problems in your code.
\item Unexpected waits, which should be immediately taken care of. After all, what's the point of profiling and optimizing your program if it is constantly waiting for something? An example of such an unexpected wait may be some anti-virus service interfering with each of your file read operations. In this case, you could have assumed that the system would buffer a large chunk of the data after the first read to make it immediately available to the application in the following calls.
\end{enumerate}

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcattention
]{Platform differences}
Wait stacks capture happen at a different time on the supported operating systems due to differences in the implementation details. For example, on Windows, the stack capture will occur when the program execution is resumed. However, on Linux, the capture will happen when the scheduler decides to preempt execution.
\end{bclogo}

\subsubsection{Hardware sampling}
\label{hardwaresampling}

While the call stack sampling is a generic software-implemented functionality of the operating system, there's another way of sampling program execution patterns. Modern processors host a wide array of different hardware performance counters, which increase when some event in a CPU core happens. These could be as simple as counting each clock cycle or as implementation-specific as counting 'retired instructions that are delivered to the back-end after the front-end had at least 1 bubble-slot for a period of 2 cycles'.

Tracy can use these counters to present you the following three statistics, which may help guide you in discovering why your code is not as fast as possible:

\begin{enumerate}
\item \emph{Instructions Per Cycle (IPC)} -- shows how many instructions were executing concurrently within a single core cycle. Higher values are better. The maximum achievable value depends on the design of the CPU, including things such as the number of execution units and their individual capabilities. Calculated as $\frac{\text{\#instructions retired}}{\text{\#cycles}}$. You can disable it with the \texttt{TRACY\_NO\_SAMPLE\_RETIREMENT} macro.
\item \emph{Branch miss rate} -- shows how frequently the CPU branch predictor makes a wrong choice. Lower values are better. Calculated as $\frac{\text{\#branch misses}}{\text{\#branch instructions}}$. You can disable it with the \texttt{TRACY\_NO\_SAMPLE\_BRANCH} macro.
\item \emph{Cache miss rate} -- shows how frequently the CPU has to retrieve data from memory. Lower values are better. The specifics of which cache level is taken into account here vary from one implementation to another. Calculated as $\frac{\text{\#cache misses}}{\text{\#cache references}}$. You can disable it with the \texttt{TRACY\_NO\_SAMPLE\_CACHE} macro.
\end{enumerate}

Each performance counter has to be collected by a dedicated Performance Monitoring Unit (PMU). However, the availability of PMUs is very limited, so you may not be able to capture all the statistics mentioned above at the same time (as each requires capture of two different counters). In such a case, you will need to manually select what needs to be sampled with the macros specified above.

If the provided measurements are not specific enough for your needs, you will need to use a profiler better tailored to the hardware you are using, such as Intel VTune, or AMD \si{\micro\relax}Prof.

Another problem to consider here is the measurement skid. It is pretty hard to accurately pinpoint the exact assembly instruction which has caused the counter to trigger. Due to this, the results you'll get may look a bit nonsense at times. For example, a branch miss may be attributed to the multiply instruction. Unfortunately, not much can be done with that, as this is exactly what the hardware is reporting. The amount of skid you will encounter depends on the specific implementation of a processor, and each vendor has its own solution to minimize it. Intel uses Precise Event Based Sampling (PEBS), which is rather good, but it still can, for example, blend the branch statistics across the comparison instruction and the following jump instruction. AMD employs its own Instruction Based Sampling (IBS), which tends to provide worse results in comparison.

Do note that the statistics presented by Tracy are a combination of two randomly sampled counters, so you should take them with a grain of salt. The random nature of sampling\footnote{The hardware counters in practice can be triggered only once per million-or-so events happening.} makes it entirely possible to count more branch misses than branch instructions or some other similar silliness. You should always cross-check this data with the count of sampled events to decide if you can reliably act upon the provided values.

\subparagraph{Availability}

Currently, the hardware performance counter readings are only available on Linux, which also includes the WSL2 layer on Windows\footnote{You may need Windows 11 and the WSL preview from Microsoft Store for this to work.}. Access to them is performed using the kernel-provided infrastructure, so what you get may depend on how your kernel was configured. This also means that the exact set of supported hardware is not known, as it depends on what has been implemented in Linux itself. At this point, the x86 hardware is fully supported (including features such as PEBS or IBS), and there's PMU support on a selection of ARM designs. The performance counter data can be captured with no need for privilege elevation.

\subsubsection{Executable code retrieval}
\label{executableretrieval}

Tracy will capture small chunks of the executable image during profiling to enable deep insight into program execution. The retrieved code can be subsequently disassembled to be inspected in detail. The profiler will perform this functionality only for functions no larger than 128 KB and only if symbol information is present.

The discovery of previously unseen executable code may result in reduced performance of real-time capture. This is especially true when the profiling session had just started. However, such behavior is expected and will go back to normal after several moments.

It would be best to be extra careful when working with non-public code, as parts of your program will be embedded in the captured trace. You can disable the collection of program code by compiling the profiled application with the \texttt{TRACY\_NO\_CODE\_TRANSFER} define. You can also strip the code from a saved trace using the \texttt{update} utility (section~\ref{dataremoval}).

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Important}
For proper program code retrieval, you can unload no module used by the application during the runtime. See section~\ref{datalifetime} for an explanation.

On Linux, Tracy will override the \texttt{dlclose} function call to prevent shared objects from being unloaded. Note that in a well-behaved program this shouldn't have any effect, as calling \texttt{dlclose} does not guarantee that the shared object will be unloaded.
\end{bclogo}

\subsubsection{Vertical synchronization}

On Windows and Linux, Tracy will automatically capture hardware Vsync events, provided that the application has access to the kernel data (privilege elevation may be needed, see section~\ref{privilegeelevation}). These events will be reported as '\texttt{[x] Vsync}' frame sets, where \texttt{x} is the identifier of a specific monitor. Note that hardware vertical synchronization might not correspond to the one seen by your application due to desktop composition, command queue buffering, and so on. Also, in some instances, when there is nothing to update on the screen, the graphic driver may choose to stop issuing screen refresh. As a result, there may be periods where no vertical synchronization events are reported.

Use the \texttt{TRACY\_NO\_VSYNC\_CAPTURE} macro to disable capture of Vsync events.

\subsection{Trace parameters}
\label{traceparameters}

Sometimes it is desired to change how the profiled application behaves during the profiling run. For example, you may want to enable or disable the capture of frame images without recompiling and restarting your program. To be able to do so you must register a callback function using the \texttt{TracyParameterRegister(callback, data)} macro, where \texttt{callback} is a function conforming to the following signature:

\begin{lstlisting}
void Callback(void* data, uint32_t idx, int32_t val)
\end{lstlisting}

The \texttt{data} parameter will have the same value as was specified in the macro. The \texttt{idx} argument is an user-defined parameter index and \texttt{val} is the value set in the profiler user interface.

To specify individual parameters, use the \texttt{TracyParameterSetup(idx, name, isBool, val)} macro. The \texttt{idx} value will be passed to the callback function for identification purposes (Tracy doesn't care what it's set to). \texttt{Name} is the parameter label,  displayed on the list of parameters. Finally, \texttt{isBool} determines if \texttt{val} should be interpreted as a boolean value, or as an integer number.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Important}
Usage of trace parameters makes profiling runs dependent on user interaction with the profiler, and thus it's not recommended to be employed if a consistent profiling environment is desired. Furthermore, interaction with the parameters is only possible in the graphical profiling application but not in the command line capture utility.
\end{bclogo}

\subsection{Source contents callback}

Tracy performs several data discovery attempts to show you the source file contents associated with the executed program, which is explained in more detail in chapter~\ref{sourceview}. However, sometimes the source files cannot be accessed without your help. For example, you may want to profile a script that is loaded by the game and which only resides in an archive accessible only by your program. Accordingly, Tracy allows inserting your own custom step at the end of the source discovery chain, with the \texttt{TracySourceCallbackRegister(callback, data)} macro, where \texttt{callback} is a function conforming to the following signature:

\begin{lstlisting}
char* Callback(void* data, const char* filename, size_t& size)
\end{lstlisting}

The \texttt{data} parameter will have the same value as was specified in the macro. The \texttt{filename} parameter contains the file name of the queried source file. Finally, the \texttt{size} parameter is used only as an out-value and does not contain any functional data.

The return value must be \texttt{nullptr} if the input file name is not accessible to the client application. If the file can be accessed, then the data size must be stored in the \texttt{size} parameter, and the file contents must be returned in a buffer allocated with the \texttt{tracy::tracy\_malloc\_fast(size)} function. Buffer contents do not need to be null-terminated. If for some reason the already allocated buffer can no longer be used, it must be freed with the \texttt{tracy::tracy\_free\_fast(ptr)} function.

Transfer of source files larger than some unspecified, but reasonably large\footnote{Let's say around 256~KB sounds reasonable.} threshold won't be performed.

\subsection{Connection status}
\label{connectionstatus}

To determine if a connection is currently established between the client and the server, you may use the \texttt{TracyIsConnected} macro, which returns a boolean value.

\section{Capturing the data}
\label{capturing}

After the client application has been instrumented, you will want to connect to it using a server, available either as a headless capture-only utility or as a full-fledged graphical profiling interface.

\subsection{Command line}

You can capture a trace using a command line utility contained in the \texttt{capture} directory. To use it you may provide the following parameters:

\begin{itemize}
\item \texttt{-o output.tracy} -- the file name of the resulting trace (required).
\item \texttt{-a address} -- specifies the IP address (or a domain name) of the client application (uses \texttt{localhost} if not provided).
\item \texttt{-p port} -- network port which should be used (optional).
\item \texttt{-f} -- force overwrite, if output file already exists.
\item \texttt{-s seconds} -- number of seconds to capture before automatically disconnecting (optional).
\end{itemize}

If no client is running at the given address, the server will wait until it can make a connection. During the capture, the utility will display the following information:

\begin{verbatim}
% ./capture -a 127.0.0.1 -o trace
Connecting to 127.0.0.1:8086...
Queue delay: 5 ns
Timer resolution: 3 ns
   1.33 Mbps / 40.4% = 3.29 Mbps | Net: 64.42 MB | Mem: 283.03 MB | Time: 10.6 s
\end{verbatim}

The \emph{queue delay} and \emph{timer resolution} parameters are calibration results of timers used by the client. The following line is a status bar, which displays: network connection speed, connection compression ratio, and the resulting uncompressed data rate; the total amount of data transferred over the network; memory usage of the capture utility; time extent of the captured data.

You can disconnect from the client and save the captured trace by pressing \keys{\ctrl + C}. If you prefer to disconnect after a fixed time, use the \texttt{-s seconds} parameter.

\subsection{Interactive profiling}
\label{interactiveprofiling}

If you want to look at the profile data in real-time (or load a saved trace file), you can use the data analysis utility contained in the \texttt{profiler} directory. After starting the application, you will be greeted with a welcome dialog (figure~\ref{welcomedialog}), presenting a bunch of useful links (\faBook{}~\emph{User manual}, \faGlobeAmericas{}~\emph{Web}, \faComment~\emph{Join chat} and \faHeart{}~\emph{Sponsor}). The \faGlobeAmericas{}~\emph{Web} button opens a drop-down list with links to the profiler's \emph{\faHome{}~Home page} and a bunch of \emph{\faVideo{}~Feature videos}.

The client \emph{address entry} field and the \faWifi{}~\emph{Connect} button are used to connect to a running client\footnote{Note that a custom port may be provided here, for example by entering '127.0.0.1:1234'.}. You can use the connection history button~\faCaretDown{} to display a list of commonly used targets, from which you can quickly select an address. You can remove entries from this list by hovering the \faMousePointer{}~mouse cursor over an entry and pressing the \keys{\del} button on the keyboard.

If you want to open a trace that you have stored on the disk, you can do so by pressing the \faFolderOpen{}~\emph{Open saved trace} button.

The \emph{discovered clients} list is only displayed if clients are broadcasting their presence on the local network\footnote{Only on IPv4 network and only within the broadcast domain.}. Each entry shows the client's address\footnote{Either as an IP address or as a hostname, if able to resolve.} (and port, if different from the default one), how long the client has been running, and the name of the profiled application. Clicking on an entry will connect to the client. Incompatible clients are grayed out and can't be connected to, but Tracy will suggest a compatible version, if able. Clicking on the \emph{\faFilter{}~Filter} toggle button will display client filtering input fields, allowing removal of the displayed entries according to their address, port number, or program name. If filters are active, a yellow \faExclamationTriangle{}~warning icon will be displayed.

\begin{figure}[h]
\centering\begin{tikzpicture}
\draw (0, 0) rectangle (4.95, -3.2);
\draw[pattern=crosshatch dots] (0, 0) rectangle+(4.95, 0.3);
\draw[rounded corners=5pt] (0.1, -0.1) rectangle+(1.1, -0.5) node [midway] {\faBook};
\draw[rounded corners=5pt] (1.3, -0.1) rectangle+(1.1, -0.5) node [midway] {\faGlobeAmericas};
\draw[rounded corners=5pt] (2.5, -0.1) rectangle+(1.1, -0.5) node [midway] {\faComment};
\draw[rounded corners=5pt] (3.7, -0.1) rectangle+(1.1, -0.5) node [midway] {\faHeart};

\draw (0.1, -0.9) rectangle+(4.1, -0.5) node [midway] {Address entry};
\draw[rounded corners=5pt] (4.33, -0.9) rectangle+(0.5, -0.5) node [midway] {\faCaretDown};
\draw[rounded corners=5pt] (0.1, -1.55) rectangle+(2, -0.5) node [midway] {\faWifi{}~Connect};
\draw[rounded corners=5pt] (2.3, -1.55) rectangle+(2.5, -0.5) node [midway] {\faFolderOpen{}~Open trace};

\draw (0.1, -2.1) node[anchor=north west] {Discovered clients: \faFilter};
\draw (0.1, -2.6) node[anchor=north west] {127.0.0.1 | 21 s | Application};
\end{tikzpicture}
\caption{Welcome dialog.}
\label{welcomedialog}
\end{figure}

Both connecting to a client and opening a saved trace will present you with the main profiler view, which you can use to analyze the data (see section~\ref{analyzingdata}).

\subsubsection{Connection information pop-up}
\label{connectionpopup}

If this is a real-time capture, you will also have access to the connection information pop-up (figure~\ref{connectioninfo}) through the \emph{\faWifi{}~Connection} button, with the capture status similar to the one displayed by the command-line utility. This dialog also shows the connection speed graphed over time and the profiled application's current frames per second and frame time measurements. The \emph{Query backlog} consists of two numbers. The first represents the number of queries that were held back due to the bandwidth volume overwhelming the available network send buffer. The second one shows how many queries are in-flight, meaning requests sent to the client but not yet answered. While these numbers drain down to zero, the performance of real time profiling may be temporarily compromised. The circle displayed next to the bandwidth graph signals the connection status. If it's red, the connection is active. If it's gray, the client has disconnected.

You can use the \faSave{}~\emph{Save trace} button to save the current profile data to a file\footnote{You should take this literally. If a live capture is in progress and a save is performed, some data may be missing from the capture and won't be saved.}. The available compression modes are discussed in sections~\ref{archival} and~\ref{fidict}. Use the \faPlug{}~\emph{Stop} button to disconnect from the client\footnote{While requesting disconnect stops retrieval of any new events, the profiler will wait for any data that is still pending for the current set of events.}. The \faExclamationTriangle{}~\emph{Discard} button is used to discard current trace.

\begin{figure}[h]
\centering\begin{tikzpicture}
\draw (0, 0.5) rectangle (6.1, -3.2);
\draw (0, 0.5) node[anchor=north west] {Connected to: 127.0.0.1};
\draw[pattern=north east lines] (0.35, -0.35) circle(0.2);
\draw (0.7, -0.1) rectangle+(3.5, -0.5) node[midway] {Bandwidth graph};
\draw (4.3, -0.1) node[anchor=north west] {1.33 Mbps};
\draw (0.1, -0.6) node[anchor=north west] {Ratio 40.4\% \hspace{5pt} Real: 3.29 Mbps};
\draw (0.1, -1.1) node[anchor=north west] {Data transferred: 23.11 MB};
\draw (0.1, -1.6) node[anchor=north west] {Query backlog: 0 + 12};
\draw (0.1, -2.1) node[anchor=north west] {FPS: 60 \hspace{5pt} Frame time: 16.7 ms};
\draw[rounded corners=5pt] (0.1, -2.6) rectangle+(2.2, -0.5) node [midway] {\faSave{}~Save trace};
\draw[rounded corners=5pt] (2.6, -2.6) rectangle+(1.3, -0.5) node [midway] {\faPlug{}~Stop};
\draw[rounded corners=5pt] (4.0, -2.6) rectangle+(2, -0.5) node [midway] {\faExclamationTriangle{}~Discard};
\end{tikzpicture}
\caption{Connection information pop-up.}
\label{connectioninfo}
\end{figure}

If frame image capture has been implemented (chapter~\ref{frameimages}), a thumbnail of the last received frame image will be provided for reference.

Suppose the profiled application opted to provide trace parameters (see section~\ref{traceparameters}) and the connection is still active. In that case, this pop-up will also contain a \emph{trace parameters} section, listing all the provided options. A callback function will be executed on the client when you change any value here.

\subsubsection{Automatic loading or connecting}

You can pass the trace file name as an argument to the profiler application to open the capture, skipping the welcome dialog. You can also use the \texttt{-a address} argument to connect to the given address automatically. Finally, to specify the network port, pass the \texttt{-p port} parameter. The profiler will use it for client connections (overridable in the UI) and for listening to client discovery broadcasts.

\subsection{Connection speed}

Tracy network bandwidth requirements depend on the amount of data collection the profiled application performs. You may expect anything between 1~Mbps and 100~Mbps data transfer rate in typical use case scenarios.

The maximum attainable connection speed is determined by the ability of the client to provide data and the ability of the server to process the received data. In an extreme conditions test performed on an i7~8700K, the maximum transfer rate peaked at 950~Mbps. In each second, the profiler could process 27~million zones and consume 1~GB of RAM.

\subsection{Memory usage}

The captured data is stored in RAM and only written to the disk when the capture finishes. This can result in memory exhaustion when you capture massive amounts of profile data or even in typical usage situations when the capture is performed over a long time. Therefore, the recommended usage pattern is to perform moderate instrumentation of the client code and limit capture time to the strict necessity.

In some cases, it may be helpful to perform an \emph{on-demand} capture, as described in section~\ref{ondemand}. In such a case, you will be able to profile only the exciting topic (e.g.,\ behavior during loading of a level in a game), ignoring all the unneeded data.

If you genuinely need to capture large traces, you have two options. Either buy more RAM or use a large swap file on a fast disk drive\footnote{The operating system can manage memory paging much better than Tracy would be ever able to.}.

\subsection{Trace versioning}

Each new release of Tracy changes the internal format of trace files. While there is a backward compatibility layer, allowing loading traces created by previous versions of Tracy in new releases, it won't be there forever. You are thus advised to upgrade your traces using the utility contained in the \texttt{update} directory.

To use it, you will need to provide the input file and the output file. The program will print a short summary when it finishes, with information about trace file versions, their respective sizes and the output trace file compression ratio:

\begin{verbatim}
% ./update old.tracy new.tracy
old.tracy (0.3.0) {916.4 MB} -> new.tracy (0.4.0) {349.4 MB, 31.53%}  9.7 s, 38.13% change
\end{verbatim}

The new file contains the same data as the old one but with an updated internal representation. Note that the whole trace needs to be loaded to memory to perform an upgrade.

\subsubsection{Archival mode}
\label{archival}

The \texttt{update} utility supports optional higher levels of data compression, which reduce disk size of traces at the cost of increased compression times. The output files have a reasonable size and are quick to save and load with the default settings. A list of available compression modes and their respective results is available in table~\ref{compressiontimes} and figures~\ref{savesize}, \ref{savetime} and~\ref{loadtime}. The following command-line options control compression mode selection:

\begin{itemize}
\item \texttt{-h} -- enables LZ4 HC compression.
\item \texttt{-e} -- uses LZ4 extreme compression.
\item \texttt{-z level} -- selects Zstandard algorithm, with a specified compression level.
\end{itemize}

\begin{table}[h]
\centering
\begin{tabular}[h]{c|c|c|c|c}
\textbf{Mode} & \textbf{Size} & \textbf{Ratio} & \textbf{Save time} & \textbf{Load time} \\ \hline
\emph{default} & 162.48 MB & 17.19\% & 1.91 \si{\second} & 470 \si{\milli\second} \\
\texttt{hc} & 77.33 MB & 8.18\% & 39.24 \si{\second} & 401 \si{\milli\second} \\
\texttt{extreme} & 72.67 MB & 7.68\% & 4:30 & 406 \si{\milli\second} \\ \hline
\texttt{zstd 1} & 63.17 MB & 6.68\% & 2.27 \si{\second} & 868 \si{\milli\second} \\
\texttt{zstd 2} & 63.29 MB & 6.69\% & 2.31 \si{\second} & 884 \si{\milli\second} \\
\texttt{zstd 3} & 62.94 MB & 6.65\% & 2.43 \si{\second} & 867 \si{\milli\second} \\
\texttt{zstd 4} & 62.81 MB & 6.64\% & 2.44 \si{\second} & 855 \si{\milli\second} \\
\texttt{zstd 5} & 61.04 MB & 6.45\% & 3.98 \si{\second} & 855 \si{\milli\second} \\
\texttt{zstd 6} & 60.27 MB & 6.37\% & 4.19 \si{\second} & 827 \si{\milli\second} \\
\texttt{zstd 7} & 61.53 MB & 6.5\% & 6.6 \si{\second} & 761 \si{\milli\second} \\
\texttt{zstd 8} & 60.44 MB & 6.39\% & 7.84 \si{\second} & 746 \si{\milli\second} \\
\texttt{zstd 9} & 59.58 MB & 6.3\% & 9.6 \si{\second} & 724 \si{\milli\second} \\
\texttt{zstd 10} & 59.36 MB & 6.28\% & 10.29 \si{\second} & 706 \si{\milli\second} \\
\texttt{zstd 11} & 59.2 MB & 6.26\% & 11.23 \si{\second} & 717 \si{\milli\second} \\
\texttt{zstd 12} & 58.51 MB & 6.19\% & 15.43 \si{\second} & 695 \si{\milli\second} \\
\texttt{zstd 13} & 56.16 MB & 5.94\% & 35.55 \si{\second} & 642 \si{\milli\second} \\
\texttt{zstd 14} & 55.76 MB & 5.89\% & 37.74 \si{\second} & 627 \si{\milli\second} \\
\texttt{zstd 15} & 54.65 MB & 5.78\% & 1:01 & 600 \si{\milli\second} \\
\texttt{zstd 16} & 50.94 MB & 5.38\% & 1:34 & 537 \si{\milli\second} \\
\texttt{zstd 17} & 50.18 MB & 5.30\% & 1:44 & 542 \si{\milli\second} \\
\texttt{zstd 18} & 49.91 MB & 5.28\% & 2:17 & 554 \si{\milli\second} \\
\texttt{zstd 19} & 46.99 MB & 4.97\% & 7:09 & 605 \si{\milli\second} \\
\texttt{zstd 20} & 46.81 MB & 4.95\% & 7:08 & 608 \si{\milli\second} \\
\texttt{zstd 21} & 45.77 MB & 4.84\% & 13:01 & 614 \si{\milli\second} \\
\texttt{zstd 22} & 45.52 MB & 4.81\% & 15:11 & 621 \si{\milli\second}
\end{tabular}
\caption{Compression results for an example trace. \\ Tests performed on Ryzen 9 3900X.}
\label{compressiontimes}
\end{table}

\begin{figure}[h]
\begin{minipage}[c]{.475\textwidth}
\begin{figure}[H]
\centering\begin{tikzpicture}
\begin{axis}[xlabel=Mode,ylabel=Size (MB), legend pos=north west, width=\textwidth]
\addplot[mark=x, red] plot coordinates {
(1, 63.17) (2, 63.29) (3, 62.94) (4, 62.81) (5, 61.04) (6, 60.27) (7, 61.53) (8, 60.44) (9, 59.58) (10, 59.36) (11, 59.2) (12, 58.51) (13, 56.16) (14, 55.76) (15, 54.65) (16, 50.94) (17, 50.18) (18, 49.91) (19, 46.99) (20, 46.81) (21, 45.77) (22, 45.52)
};
\addlegendentry{zstd}
\addplot[mark=o, blue] plot coordinates { (23, 162.48) };
\addlegendentry{default}
\addplot[mark=*, blue] plot coordinates { (24, 77.33) };
\addlegendentry{hc}
\addplot[mark=triangle*, blue] plot coordinates { (25, 72.67) };
\addlegendentry{extreme}
\end{axis}
\end{tikzpicture}
\caption{Plot of trace sizes for different compression modes (see table~\ref{compressiontimes}).}
\label{savesize}
\end{figure}
\end{minipage}%
\hspace{0.04\textwidth}%
\begin{minipage}[c]{.475\textwidth}
\begin{figure}[H]
\centering\begin{tikzpicture}
\begin{semilogyaxis}[xlabel=Mode,ylabel=Time (s), legend pos=north west, width=\textwidth]
\addplot[mark=x, red] plot coordinates {
(1, 2.27) (2, 2.31) (3, 2.43) (4, 2.44) (5, 3.98) (6, 4.19) (7, 6.6) (8, 7.84) (9, 9.6) (10, 10.29) (11, 11.23) (12, 15.43) (13, 35.55) (14, 37.74) (15, 61) (16, 94) (17, 104) (18, 137) (19, 429) (20, 428) (21, 781) (22, 911)
};
\addlegendentry{zstd}
\addplot[mark=o, blue] plot coordinates { (23, 1.91) };
\addlegendentry{default}
\addplot[mark=*, blue] plot coordinates { (24, 39.24) };
\addlegendentry{hc}
\addplot[mark=triangle*, blue] plot coordinates { (25, 270) };
\addlegendentry{extreme}
\end{semilogyaxis}
\end{tikzpicture}
\caption{Logarithmic plot of trace compression times for different compression modes (see table~\ref{compressiontimes}).}
\label{savetime}
\end{figure}
\end{minipage}
\end{figure}

\begin{figure}[H]
\centering\begin{tikzpicture}
\begin{axis}[xlabel=Mode,ylabel=Time (ms), legend pos=south west, width=0.475\textwidth]
\addplot[mark=x, red] plot coordinates {
(1, 868) (2, 884) (3, 867) (4, 855) (5, 855) (6, 827) (7, 761) (8, 746) (9, 724) (10, 706) (11, 717) (12, 695) (13, 642) (14, 627) (15, 600) (16, 537) (17, 542) (18, 554) (19, 605) (20, 608) (21, 614) (22, 621)
};
\addlegendentry{zstd}
\addplot[mark=o, blue] plot coordinates { (23, 470) };
\addlegendentry{default}
\addplot[mark=*, blue] plot coordinates { (24, 401) };
\addlegendentry{hc}
\addplot[mark=triangle*, blue] plot coordinates { (25, 406) };
\addlegendentry{extreme}
\end{axis}
\end{tikzpicture}
\caption{Plot of trace load times for different compression modes (see table~\ref{compressiontimes}).}
\label{loadtime}
\end{figure}

Trace files created using the \emph{default}, \emph{hc} and \emph{extreme} modes are optimized for fast decompression and can be further compressed using file compression utilities. For example, using 7-zip results in archives of the following sizes: 77.2 MB, 54.3 MB, 52.4 MB.

For archival purposes, it is, however, much better to use the \emph{zstd} compression modes, which are faster, compress trace files more tightly, and are directly loadable by the profiler, without the intermediate decompression step.

\subsubsection{Frame images dictionary}
\label{fidict}

Frame images have to be compressed individually so that there are no delays during random access to the contents of any image. Unfortunately, because of this, there is no reuse of compression state between similar (or even identical) images, which leads to increased memory consumption. The profiler can partially remedy this by enabling the calculation of an optional frame images dictionary with the \texttt{-d} command line parameter.

Saving a trace with frame images dictionary-enabled will need some extra time, depending on the amount of image data you have captured. Loading such a trace will also be slower, but not by much. How much RAM the dictionary will save depends on the similarity of frame images. Be aware that post-processing effects such as artificial film grain have a subtle impact on image contents, which is significant in this case.

The dictionary cannot be used when you are capturing a trace.

\subsubsection{Data removal}
\label{dataremoval}

In some cases you may want to share just a portion of the trace file, omitting sensitive data such as source file cache, or machine code of the symbols. This can be achieved using the \texttt{-s flags} command line option. To select what kind of data is to be stripped, you need to provide a list of flags selected from the following:

\begin{itemize}
\item \texttt{l} -- locks.
\item \texttt{m} -- messages.
\item \texttt{p} -- plots.
\item \texttt{M} -- memory.
\item \texttt{i} -- frame images.
\item \texttt{c} -- context switches.
\item \texttt{s} -- sampling data.
\item \texttt{C} -- symbol code.
\item \texttt{S} -- source file cache.
\end{itemize}

Flags can be concatenated. For example specifying \texttt{-s CSi} will remove symbol code, source file cache, and frame images in the destination trace file.

\subsection{Source file cache scan}

Sometimes access to source files may not be possible during the capture. This may be due to capturing the trace on a machine without the source files on disk, use of paths relative to the build directory, clash of file location schemas (e.g., on Windows, you can have native paths, like \texttt{C:\textbackslash{}directory\textbackslash{}file} and WSL paths, like \texttt{/mnt/c/directory/file}, pointing to the same file), and so on.

You may force a recheck of the source file availability during the update process with the \texttt{-c} command line parameter. All the source files missing from the cache will be then scanned again and added to the cache if they do pass the validity checks (see section~\ref{sourceview}).

\subsection{Instrumentation failures}
\label{instrumentationfailures}

In some cases, your program may be incorrectly instrumented. For example, you could have unbalanced zone begin and end events or report a memory-free event without first reporting a memory allocation event. When Tracy detects such misbehavior, it immediately terminates the connection with the client and displays an error message.

\section{Analyzing captured data}
\label{analyzingdata}

You have instrumented your application, and you have captured a profiling trace. Now you want to look at the collected data. You can do this in the application contained in the \texttt{profiler} directory.

The workflow is identical, whether you are viewing a previously saved trace or if you're performing a live capture, as described in section~\ref{interactiveprofiling}.

\subsection{Time display}

In most cases Tracy will display an approximation of time value, depending on how big it is. For example, a short time range will be displayed as 123~\si{\nano\second}, and some longer ones will be shortened to 123.45~\si{\micro\second}, 123.45~\si{\milli\second}, 12.34~\si{\second}, 1:23.4, 12:34:56, or even 1d12:34:56 to indicate more than a day has passed.

While such a presentation makes time values easy to read, it is not always appropriate. For example, you may have multiple events happen at a time approximated to 1:23.4, giving you the precision of only $\sfrac{1}{10}$ of a second. And there's certainly a lot that can happen in 100~\si{\milli\second}.

An alternative time display is used in appropriate places to solve this problem. It combines a day--hour--minute--second value with full nanosecond resolution, resulting in values such as 1:23~456,789,012~\si{\nano\second}.

\subsection{Main profiler window}

The main profiler window is split into three sections, as seen in figure~\ref{mainwindow}: the control menu, the frame time graph, and the timeline display.

\begin{figure}[h]
\centering\begin{tikzpicture}
\draw (0, 0) rectangle (16.1, -5.5);
\draw[pattern=crosshatch dots] (0, 0) rectangle+(16.1, 0.3);
\draw[rounded corners=5pt] (0.1, -0.1) rectangle+(0.5, -0.5) node [midway] {\faPowerOff};
\draw[rounded corners=5pt] (0.7, -0.1) rectangle+(1.8, -0.5) node [midway] {\faCog{} Options};
\draw[rounded corners=5pt] (2.6, -0.1) rectangle+(2.2, -0.5) node [midway] {\faTags{} Messages};
\draw[rounded corners=5pt] (4.9, -0.1) rectangle+(2.1, -0.5) node [midway] {\faSearch{} Find zone};
\draw[rounded corners=5pt] (7.1, -0.1) rectangle+(2, -0.5) node [midway] {\faSortAmountUp{} Statistics};
\draw[rounded corners=5pt] (9.2, -0.1) rectangle+(2, -0.5) node [midway] {\faMemory{} Memory};
\draw[rounded corners=5pt] (11.3, -0.1) rectangle+(2.1, -0.5) node [midway] {\faBalanceScale{} Compare};
\draw[rounded corners=5pt] (13.5, -0.1) rectangle+(1.3, -0.5) node [midway] {\faFingerprint{} Info};
\draw[rounded corners=5pt] (14.9, -0.1) rectangle+(0.5, -0.5) node [midway] {\faTools{}};
\draw[rounded corners=5pt] (15.5, -0.1) rectangle+(0.5, -0.5) node [midway] {\faSearchPlus{}};
\draw[rounded corners=5pt] (0.1, -0.7) rectangle+(0.4, -0.5) node [midway] {\faCaretLeft};
\draw (0.6, -0.7) node[anchor=north west] {Frames: 364};
\draw[rounded corners=5pt] (2.8, -0.7) rectangle+(0.4, -0.5) node [midway] {\faCaretRight};
\draw[rounded corners=5pt] (3.3, -0.7) rectangle+(0.5, -0.5) node [midway] {\faCaretDown};
\draw (4, -0.65) node[anchor=north west] {\faEye~52.7 ms \hspace{5pt} \faDatabase~6.06 s \hspace{5pt} \faMemory~195.2 MB};
\draw[dashed] (10.1, -0.75) rectangle+(3.2, -0.4) node[midway] {Notification area};

\draw (0.1, -1.3) rectangle+(15.9, -1) node [midway] {Frame time graph};
\draw (0.1, -2.4) rectangle+(15.9, -3) node [midway] {Timeline view};
\end{tikzpicture}
\caption{Main profiler window. Note that this manual has split the top line of buttons into two rows.}
\label{mainwindow}
\end{figure}

\subsubsection{Control menu}
\label{controlmenu}

The control menu (top row of buttons) provides access to various profiler features. The buttons perform the following actions:

\begin{itemize}
\item \emph{\faWifi{}~Connection} -- Opens the connection information popup (see section~\ref{connectionpopup}). Only available when live capture is in progress.
\item \emph{\faPowerOff{} Close} -- This button unloads the current profiling trace and returns to the welcome menu, where another trace can be loaded. In live captures it is replaced by \emph{\faPause{}~Pause}, \emph{\faPlay{}~Resume} and \emph{\faSquare{}~Stopped} buttons.
\item \emph{\faPause{} Pause} -- While a live capture is in progress, the profiler will display recent events, as either the last three fully captured frames, or a certain time range. You can use this to see the current behavior of the program. The pause button\footnote{Or perform any action on the timeline view, apart from changing the zoom level.} will stop the automatic updates of the timeline view (the capture will still be progressing).
\item \emph{\faPlay{} Resume} -- This button allows to resume following the most recent events in a live capture. You will have selection of one of the following options: \emph{\faSearchPlus{}~Newest three frames}, or \emph{\faRulerHorizontal{}~Use current zoom level}.
\item \emph{\faSquare{} Stopped} -- Inactive button used to indicate that the client application was terminated.
\item \emph{\faCog{} Options} -- Toggles the settings menu (section~\ref{options}).
\item \emph{\faTags{} Messages} -- Toggles the message log window (section~\ref{messages}), which displays custom messages sent by the client, as described in section~\ref{messagelog}.
\item \emph{\faSearch{} Find zone} -- This buttons toggles the find zone window, which allows inspection of zone behavior statistics (section~\ref{findzone}).
\item \emph{\faSortAmountUp{} Statistics} -- Toggles the statistics window, which displays zones sorted by their total time cost (section~\ref{statistics}).
\item \emph{\faMemory{} Memory} -- Various memory profiling options may be accessed here (section~\ref{memorywindow}).
\item \emph{\faBalanceScale{} Compare} -- Toggles the trace compare window, which allows you to see the performance difference between two profiling runs (section~\ref{compare}).
\item \emph{\faFingerprint{} Info} -- Show general information about the trace (section~\ref{traceinfo}).
\item \emph{\faTools{} Tools} -- Allows access to optional data collected during capture. Some choices might be unavailable.
\begin{itemize}
\item \emph{\faPlay{}~Playback} -- If frame images were captured (section~\ref{frameimages}), you will have option to open frame image playback window, described in chapter~\ref{playback}.
\item \emph{\faSlidersH{}~CPU~data} -- If context switch data was captured (section~\ref{contextswitches}), this button will allow inspecting what was the processor load during the capture, as described in section~\ref{cpudata}.
\item \emph{\faStickyNote{}~Annotations} -- If annotations have been made (section~\ref{annotatingtrace}), you can open a list of all annotations, described in chapter~\ref{annotationlist}.
\item \emph{\faRuler{}~Limits} -- Displays time range limits window (section~\ref{timeranges}).
\item \emph{\faHourglassHalf{}~Wait stacks} -- If sampling was performed, an option to display wait stacks may be available. See chapter~\ref{waitstacks} for more details.
\end{itemize}
\item \emph{\faSearchPlus{}~Display scale} -- Enables run-time resizing of the displayed content. This may be useful in environments with potentially reduced visibility, e.g. during a presentation. Note that this setting is independent to the UI scaling coming from the system DPI settings.
\end{itemize}

The frame information block\footnote{Visible only if frame instrumentation was included in the capture.} consists of four elements: the current frame set name along with the number of captured frames (click on it with the \LMB{}~left mouse button to go to a specified frame), the two navigational buttons \faCaretLeft{} and \faCaretRight{}, which allow you to focus the timeline view on the previous or next frame, and the frame set selection button \faCaretDown{}, which is used to switch to another frame set\footnote{See section~\ref{framesets} for another way to change the active frame set.}. For more information about marking frames, see section~\ref{markingframes}.

The following three items show the \emph{\faEye{}~view time range}, the \emph{\faDatabase{}~time span} of the whole capture (clicking on it with the \MMB{} middle mouse button will set the view range to the entire capture), and the \emph{\faMemory{}~memory usage} of the profiler.

\paragraph{Notification area}

The notification area displays informational notices, for example, how long it took to load a trace from the disk. A pulsating dot next to the \faTasks~icon indicates that some background tasks are being performed that may need to be completed before full capabilities of the profiler are available. If a crash was captured during profiling (section~\ref{crashhandling}), a \emph{\faSkull{}~crash} icon will be displayed. The red \faSatelliteDish{}~icon indicates that queries are currently being backlogged, while the same yellow icon indicates that some queries are currently in-flight (see chapter~\ref{connectionpopup} for more information).

If the drawing of timeline elements was disabled in the options menu (section~\ref{options}), the profiler will use the following orange icons to remind you about that fact. Click on the icons to enable drawing of the selected elements. Note that collapsed labels (section~\ref{zoneslocksplots}) are not taken into account here.

\begin{itemize}
\item \faExpand{} -- Display of empty labels is enabled.
\item \faHiking{} -- Context switches are hidden.
\item \faSlidersH{} -- CPU data is hidden.
\item \faEye{} -- GPU zones are hidden.
\item \faMicrochip{} -- CPU zones are hidden.
\item \faLock{} -- Locks are hidden.
\item \faSignature{} -- Plots are hidden.
\item \faGhost{} -- Ghost zones are not displayed.
\item \faLowVision{} -- At least one timeline item (e.g. a single thread, a single plot, a single lock, etc.) is hidden.
\end{itemize}

\subsubsection{Frame time graph}
\label{frametimegraph}

The graph of the currently selected frame set (figure~\ref{frametime}) provides an outlook on the time spent in each frame, allowing you to see where the problematic frames are and to navigate to them quickly.

\begin{figure}[h]
\centering\begin{tikzpicture}
\fill[black!20] (2.15, 0) rectangle+(1.2, 1);

\draw (0, 0) rectangle (10, 1);

\draw[pattern=north east lines] (0.1, 0) rectangle+(0.2, 0.2);
\draw[pattern=north east lines] (0.4, 0) rectangle+(0.2, 0.21);
\draw[pattern=north east lines] (0.7, 0) rectangle+(0.2, 0.18);
\draw[pattern=north east lines] (1, 0) rectangle+(0.2, 0.22);
\draw[pattern=north east lines] (1.3, 0) rectangle+(0.2, 0.7);
\draw[pattern=north east lines] (1.6, 0) rectangle+(0.2, 0.2);
\draw[pattern=north east lines] (1.9, 0) rectangle+(0.2, 0.31);
\draw[pattern=north east lines] (2.2, 0) rectangle+(0.2, 0.12);
\draw[pattern=north east lines] (2.5, 0) rectangle+(0.2, 0.2);
\draw[pattern=north east lines] (2.8, 0) rectangle+(0.2, 0.2);
\draw[pattern=north east lines] (3.1, 0) rectangle+(0.2, 0.25);
\draw[pattern=north east lines] (3.4, 0) rectangle+(0.2, 0.19);
\draw[pattern=north east lines] (3.7, 0) rectangle+(0.2, 0.23);
\draw[pattern=north east lines] (4, 0) rectangle+(0.2, 0.19);
\draw[pattern=north east lines] (4.3, 0) rectangle+(0.2, 0.2);
\draw[pattern=north east lines] (4.6, 0) rectangle+(0.2, 0.16);
\draw[pattern=north east lines] (4.9, 0) rectangle+(0.2, 0.21);
\draw[pattern=north east lines] (5.2, 0) rectangle+(0.2, 0.2);
\draw[pattern=north east lines] (5.5, 0) rectangle+(0.2, 0.8);
\draw[pattern=north east lines] (5.8, 0) rectangle+(0.2, 0.1);
\draw[pattern=north east lines] (6.1, 0) rectangle+(0.2, 0.21);
\draw[pattern=north east lines] (6.4, 0) rectangle+(0.2, 0.2);
\draw[pattern=north east lines] (6.7, 0) rectangle+(0.2, 0.2);
\draw[pattern=north east lines] (7, 0) rectangle+(0.2, 0.28);
\draw[pattern=north east lines] (7.3, 0) rectangle+(0.2, 0.22);
\draw[pattern=north east lines] (7.6, 0) rectangle+(0.2, 0.16);
\draw[pattern=north east lines] (7.9, 0) rectangle+(0.2, 0.2);
\draw[pattern=north east lines] (8.2, 0) rectangle+(0.2, 0.21);
\draw[pattern=north east lines] (8.5, 0) rectangle+(0.2, 0.18);
\draw[pattern=north east lines] (8.8, 0) rectangle+(0.2, 0.2);

\draw[dotted] (0, 0.325) -- +(10, 0);
\draw[dotted] (0, 0.6) -- +(10, 0);
\draw[dotted] (0, 0.8) -- +(10, 0);
\end{tikzpicture}
\caption{Frame time graph.}
\label{frametime}
\end{figure}

Each bar displayed on the graph represents a unique frame in the current frame set\footnote{Unless the view is zoomed out and multiple frames are merged into one column.}. The progress of time is in the right direction. The bar height indicates the time spent in the frame, complemented by the color information, which depends on the target FPS value. You can set the desired FPS in the options menu (see section~\ref{options}).

\begin{itemize}
\item If the bar is \emph{blue}, then the frame met the \emph{best} time of twice the target FPS (represented by the green target line).
\item If the bar is \emph{green}, then the frame met the \emph{good} time of target FPS (represented by the yellow line).
\item If the bar is \emph{yellow}, then the frame met the \emph{bad} time of half the FPS (represented by the red target line).
\item If the bar is \emph{red}, then the frame didn't meet any time limits.
\end{itemize}

The frames visible on the timeline are marked with a violet box drawn over them.

When a zone is displayed in the find zone window (section~\ref{findzone}), the coloring of frames may be changed, as described in section~\ref{frametimefindzone}.

Moving the \faMousePointer{} mouse cursor over the frames displayed on the graph will display a tooltip with information about frame number, frame time, frame image (if available, see chapter~\ref{frameimages}), etc. Such tooltips are common for many UI elements in the profiler and won't be mentioned later in the manual.

You may focus the timeline view on the frames by clicking or dragging the \LMB{}~left mouse button on the graph. The graph may be scrolled left and right by dragging the \RMB{}~right mouse button over the graph. Finally, you may zoom the view in and out by using the \Scroll{}~mouse wheel. If the view is zoomed out, so that multiple frames are merged into one column, the profiler will use the highest frame time to represent the given column.

Clicking the \LMB{}~left mouse button on the graph while the \keys{\ctrl}~key is pressed will open the frame image playback window (section~\ref{playback}) and set the playback to the selected frame. See section~\ref{frameimages} for more information about frame images.

\subsubsection{Timeline view}

The timeline is the most crucial element of the profiler UI. All the captured data is displayed there, laid out on the horizontal axis, according to time flow. Where there was no profiling performed, the timeline is dimmed out. The view is split into three parts: the time scale, the frame sets, and the combined zones, locks, and plots display.

\subparagraph{Collapsed items}
\label{collapseditems}

Due to extreme differences in time scales, you will almost constantly see events too small to be displayed on the screen. Such events have preset minimum size (so they can be seen) and are marked with a zig-zag pattern to indicate that you need to zoom in to see more detail.

The zig-zag pattern can be seen applied to frame sets on figure~\ref{framesetsfig}, and zones on figure~\ref{zoneslocks}.

\paragraph{Time scale}

The time scale is a quick aid in determining the relation between screen space and the time it represents (figure~\ref{timescale}).

\begin{figure}[h]
\centering\begin{tikzpicture}
\foreach \x in {0,1,2,...,10} {
\draw (\x+0, 0) -- +(0, -0.4);
\draw (\x+0.1, 0) -- +(0, -0.2);
\draw (\x+0.2, 0) -- +(0, -0.2);
\draw (\x+0.3, 0) -- +(0, -0.2);
\draw (\x+0.4, 0) -- +(0, -0.2);
\draw (\x+0.5, 0) -- +(0, -0.3);
\draw (\x+0.6, 0) -- +(0, -0.2);
\draw (\x+0.7, 0) -- +(0, -0.2);
\draw (\x+0.8, 0) -- +(0, -0.2);
\draw (\x+0.9, 0) -- +(0, -0.2); }
\draw (11, 0) -- +(0, -0.4);

\draw (-0.2, -0.4) node[anchor=north west] {+13.76 s};
\draw (1.85, -0.4) node[anchor=north west] {20 \si{\micro\second}};
\draw (3.85, -0.4) node[anchor=north west] {40 \si{\micro\second}};
\draw (5.85, -0.4) node[anchor=north west] {60 \si{\micro\second}};
\draw (7.85, -0.4) node[anchor=north west] {80 \si{\micro\second}};
\draw (9.85, -0.4) node[anchor=north west] {100 \si{\micro\second}};
\end{tikzpicture}
\caption{Time scale.}
\label{timescale}
\end{figure}

The leftmost value on the scale represents when the timeline starts. The rest of the numbers label the notches on the scale, with some numbers omitted if there's no space to display them.

Hovering the \faMousePointer{}~mouse pointer over the time scale will display a tooltip with the exact timestamp at the position of the mouse cursor.

\paragraph{Frame sets}
\label{framesets}

Frames from each frame set are displayed directly underneath the time scale. Each frame set occupies a separate row. The currently selected frame set is highlighted with bright colors, with the rest dimmed out.

\begin{figure}[h]
\centering\begin{tikzpicture}
\draw[densely dotted] (-0.05, 0) -- +(0, -1.5);
\draw (0, 0) -- +(0, -0.5);
\draw (0, -0.25) -- +(1, 0) node[anchor=west] {Frame 312 (6.99 \si{\milli\second})};
\draw (4.3, -0.25) -- +(1, 0);
\draw (5.3, 0) -- +(0, -0.5);
\draw[densely dotted] (5.35, 0) -- +(0, -1.5);
\draw[decorate,decoration=zigzag] (5.4, -0.25) -- +(1.25, 0);
\draw[densely dotted] (6.7, 0) -- +(0, -1.5);
\draw (6.75, 0) -- +(0, -0.5);
\draw (6.75, -0.25) -- +(0.5, 0) node[anchor=west] {Frame 347 (5.24 \si{\milli\second})};
\draw (10.5, -0.25) -- +(0.5, 0);
\draw (11, 0) -- +(0, -0.5);
\draw[densely dotted] (11.05, 0) -- +(0, -1.5);
\draw (11.1, 0) -- +(0, -0.5);
\draw (11.1, -0.25) -- +(0.5, 0) node[anchor=west] {1.63 \si{\milli\second}};
\draw (13, -0.25) -- +(0.5, 0);
\draw (13.5, 0) -- +(0, -0.5);
\draw[densely dotted] (13.55, 0) -- +(0, -1.5);
\draw (13.6, 0) -- +(0, -0.5);
\draw (13.6, -0.25) -- +(0.5, 0);
\draw (14.1, 0) -- +(0, -0.5);
\draw[densely dotted] (14.15, 0) -- +(0, -1.5);
\end{tikzpicture}
\caption{Frames on the timeline.}
\label{framesetsfig}
\end{figure}

In figure~\ref{framesetsfig} we can see the fully described frames~312 and 347. The description consists of the frame name, which is \emph{Frame} for the default frame set (section~\ref{markingframes}) or the name you used for the secondary name set (section~\ref{secondaryframeset}), the frame number, and the frame time. Since frame~348 is too small to be fully labeled, only the frame time is shown. On the other hand, frame~349 is even smaller, with no space for any text. Moreover, frames~313~to~346 are too small to be displayed individually, so they are replaced with a zig-zag pattern, as described in section~\ref{collapseditems}.

You can also see frame separators are projected down to the rest of the timeline view. Note that only the separators for the currently selected frame set are displayed. You can make a frame set active by clicking the \LMB{}~left mouse button on a frame set row you want to select (also see section~\ref{controlmenu}).

Clicking the \MMB{} middle mouse button on a frame will zoom the view to the extent of the frame.

If a frame has an associated frame image (see chapter~\ref{frameimages}), you can hold the \keys{\ctrl} key and click the \LMB{}~left mouse button on the frame to open the frame image playback window (see chapter~\ref{playback}) and set the playback to the selected frame.

If the \emph{\faFlagCheckered{}~Draw frame targets} option is enabled (see section~\ref{options}), time regions in frames exceeding the set target value will be marked with a red background.

\paragraph{Zones, locks and plots display}
\label{zoneslocksplots}

You will find the zones with locks and their associated threads on this combined view. The plots are graphed right below.

\begin{figure}[h]
\centering\begin{tikzpicture}
\draw(0, 0.55) -- (0.2, 0.55) -- (0.1, 0.35) -- (0, 0.55);
\draw(0.25, 0.7) node[anchor=north west] {Main thread};
\draw[densely dotted] (0, 0.2) -- +(15, 0);

\draw(1.2, -0.025) node[circle,draw,inner sep=0pt,minimum size=4] {};
\draw(2.2, -0.025) node[circle,draw,inner sep=0pt,minimum size=4] {};
\draw(3.3, -0.025) node[circle,draw,inner sep=0pt,minimum size=4] {};
\draw(5, -0.025) node[circle,draw,inner sep=0pt,minimum size=4] {};
\draw(6.2, -0.025) node[circle,draw,inner sep=0pt,minimum size=4] {};
\draw(7, -0.025) node[circle,draw,inner sep=0pt,minimum size=4] {};
\draw(8.2, -0.025) node[circle,draw,inner sep=0pt,minimum size=4] {};
\draw(9.8, -0.025) node[circle,draw,inner sep=0pt,minimum size=4] {};
\draw(11.7, -0.025) node[circle,draw,inner sep=0pt,minimum size=4] {};
\draw(12.7, -0.025) node[circle,draw,inner sep=0pt,minimum size=4] {};

\draw[dotted, thick] (0, -0.25) -- (1, -0.25);
\draw[thick] (1, -0.25) -- (3.8, -0.25);
\draw[dotted, thick] (3.8, -0.25) -- (4.8, -0.25 );
\draw[thick] (4.8, -0.25) -- (10.5, -0.25);
\draw[dotted, thick] (10.5, -0.25) -- (11, -0.25);
\draw[thick] (11, -0.25) -- (14.2, -0.25);
\draw[dotted, thick] (14.2, -0.25) -- (15, -0.25);

\draw(1.5, -0.5) rectangle+(5, -0.5) node[midway] {Update};
\draw(2, -1) rectangle+(0.75, -0.5) node[midway] {6};
\draw[densely dotted, decorate,decoration=zigzag] (2, -1.25) -- +(0.75, 0 );
\draw(3, -1) rectangle+(3, -0.5) node[midway] {Physics};
\draw(3.2, -1.5) rectangle+(0.5, -0.5);
\draw(4.8, -1.5) rectangle+(0.3, -0.5);
\draw(5.1, -1.5) rectangle+(0.4, -0.5);

\draw(7.5, -0.5) rectangle+(6.5, -0.5) node[midway] {Render};

\draw(0, -2.5) node[anchor=north west] {Physics lock};
\draw[pattern=crosshatch dots] (3.1, -2.5) rectangle+(2.5, -0.5);

\draw(0, -3.65) -- (0.2, -3.65) -- (0.1, -3.85) -- (0, -3.65);
\draw(0.25, -3.5) node[anchor=north west] {Streaming thread \faGhost};
\draw[densely dotted] (0, -4) -- +(15, 0);

\draw[thick] (0, -4.25) -- (6.1, -4.25);
\draw[dotted, thick] (6.1, -4.25) -- (9.7, -4.25);
\draw[thick] (9.7, -4.25) -- (15, -4.25);

\draw(5.5, -4) -- (5.4, -3.85) -- (5.6, -3.85) -- (5.5, -4);
\draw(0, -4.5) -- (6, -4.5) -- (6, -5) -- (0, -5);
\draw(0, -4.5) node[anchor=north west] {Streaming job};
\draw(15, -4.5) -- (10, -4.5) -- (10, -5) -- (15, -5);
\draw(15, -4.5) node[anchor=north east] {Streaming job};
\draw(10.4, -5) rectangle+(3, -0.5) node[midway] {Load image};
\end{tikzpicture}
\caption{Zones and locks display.}
\label{zoneslocks}
\end{figure}

The left-hand side \emph{index area} of the timeline view displays various labels (threads, locks), which can be categorized in the following way:

\begin{itemize}
\item \emph{Light blue label} -- GPU context. Multi-threaded Vulkan, OpenCL, and Direct3D 12 contexts are additionally split into separate threads.
\item \emph{Pink label} -- CPU data graph.
\item \emph{White label} -- A CPU thread. It will be replaced by a bright red label in a thread that has crashed (section~\ref{crashhandling}). If automated sampling was performed, clicking the~\LMB{}~left mouse button on the \emph{\faGhost{}~ghost zones} button will switch zone display mode between 'instrumented' and 'ghost.'
\item \emph{Green label} -- Fiber, coroutine, or any other sort of cooperative multitasking 'green thread.'
\item \emph{Light red label} -- Indicates a lock.
\item \emph{Yellow label} -- Plot.
\end{itemize}

Labels accompanied by the \faCaretDown{}~symbol can be collapsed out of the view to reduce visual clutter. Hover the~\faMousePointer{}~mouse pointer over the label to display additional information. Click the \MMB{}~middle mouse button on a title to zoom the view to the extent of the label contents. Finally, click the \RMB{}~right mouse button on a label to display the context menu with available actions:

\begin{itemize}
\item \emph{\faEyeSlash{}~Hide} -- Hides the label along with the content associated to it. To make the label visible again, you must find it in the options menu (section~\ref{options}).
\end{itemize}

\subparagraph{Zones}

In an example in figure~\ref{zoneslocks} you can see that there are two threads: \emph{Main thread} and \emph{Streaming thread}\footnote{By clicking on a thread name, you can temporarily disable the display of the zones in this thread.}. We can see that the \emph{Main thread} has two root level zones visible: \emph{Update} and \emph{Render}. The \emph{Update} zone is split into further sub-zones, some of which are too small to be displayed at the current zoom level. This is indicated by drawing a zig-zag pattern over the merged zones box (section~\ref{collapseditems}), with the number of collapsed zones printed in place of the zone name. We can also see that the \emph{Physics} zone acquires the \emph{Physics lock} mutex for most of its run time.

Meanwhile, the \emph{Streaming thread} is performing some \emph{Streaming jobs}. The first \emph{Streaming job} sent a message (section~\ref{messagelog}). In addition to being listed in the message log, it is indicated by a triangle over the thread separator. When multiple messages are in one place, the triangle outline shape changes to a filled triangle.

At high zoom levels, the zones will be displayed with additional markers, as presented in figure~\ref{inaccuracy}. The red regions at the start and end of a zone indicate the cost associated with recording an event (\emph{Queue delay}). The error bars show the timer inaccuracy (\emph{Timer resolution}). Note that these markers are only \emph{approximations}, as many factors can impact the actual cost of capturing a zone, for example, cache effects or CPU frequency scaling, which is unaccounted for (see section~\ref{checkenvironmentcpu}).

\begin{figure}[h]
\centering\begin{tikzpicture}
\draw(0, 0) rectangle+(5, 0.5) node [midway] {Zone};
\draw[pattern=crosshatch dots] (0, 0) rectangle+(1, 0.5);
\draw[pattern=crosshatch dots] (5, 0) rectangle+(1, 0.5);
\draw(-0.5, 0.35) -- (-0.5, 0.15);
\draw(0.5, 0.35) -- (0.5, 0.15);
\draw(-0.5, 0.25) -- (0.5, 0.25);
\draw(4.5, 0.35) -- (4.5, 0.15);
\draw(5.5, 0.35) -- (5.5, 0.15);
\draw(4.5, 0.25) -- (5.5, 0.25);
\draw(0, -0.2) -- (0, -0.3) -- (5, -0.3) -- (5, -0.2);
\draw(2.5, -0.3) node[anchor=north] {Zone extent};
\end{tikzpicture}
\caption{Approximation of timer inaccuracies and zone collection cost.}
\label{inaccuracy}
\end{figure}

The GPU zones are displayed just like CPU zones, with an OpenGL/Vulkan/Direct3D/OpenCL context in place of a thread name.

Hovering the \faMousePointer{} mouse pointer over a zone will highlight all other zones that have the exact source location with a white outline. Clicking the \LMB{}~left mouse button on a zone will open the zone information window (section~\ref{zoneinfo}). Holding the \keys{\ctrl} key and clicking the \LMB{}~left mouse button on a zone will open the zone statistics window (section~\ref{findzone}). Clicking the \MMB{}~middle mouse button on a zone will zoom the view to the extent of the zone.

\subparagraph{Ghost zones}

You can enable the view of ghost zones (not pictured on figure~\ref{zoneslocks}, but similar to standard zones view) by clicking on the \emph{\faGhost{}~ghost zones} icon next to the thread label, available if automated sampling (see chapter~\ref{sampling}) was performed. Ghost zones will also be displayed by default if no instrumented zones are available for a given thread to help with pinpointing functions that should be instrumented.

Ghost zones represent true function calls in the program, periodically reported by the operating system. Due to the limited sampling resolution, you need to take great care when looking at reported timing data. While it may be apparent that some small function requires a relatively long time to execute, for example, 125~\si{\micro\second} (8~kHz~sampling rate), in reality, this time represents a period between taking two distinct samples, not the actual function run time. Similarly, two (or more) separate function calls may be represented as a single ghost zone because the profiler doesn't have the information needed to know about the actual lifetime of a sampled function.

Another common pitfall to watch for is the order of presented functions. \emph{It is not what you expect it to be!} Read chapter~\ref{readingcallstacks} for critical insight on how call stacks might seem nonsensical at first and why they aren't.

The available information about ghost zones is quite limited, but it's enough to give you a rough outlook on the execution of your application. The timeline view alone is more than any other statistical profiler can present. In addition, Tracy correctly handles inlined function calls, which are indicated by a darker background of ghost zones. Lastly, zones representing kernel-mode functions are displayed with red function names.

Clicking the \LMB{}~left mouse button on a ghost zone will open the corresponding source file location, if able (see chapter~\ref{sourceview} for conditions). There are three ways in which source locations can be assigned to a ghost zone:

\begin{enumerate}
\item If the selected ghost zone is \emph{not} an inline frame and its symbol data has been retrieved, the source location points to the function entry location (first line of the function).
\item If the selected ghost zone is \emph{not} an inline frame, but its symbol data is not available, the source location will point to a semi-random location within the function body (i.e. to one of the sampled addresses in the program, but not necessarily the one representing the selected time stamp, as multiple samples with different addresses may be merged into one ghost zone).
\item If the selected ghost zone \emph{is} an inline frame, the source location will point to a semi-random location within the inlined function body (see details in the above point). It is impossible to go to such a function's entry location, as it doesn't exist in the program binary. Inlined functions begin in the parent function.
\end{enumerate}

\subparagraph{Call stack samples}

The row of dots right below the \emph{Main thread} label shows call stack sample points, which may have been automatically captured (see chapter~\ref{sampling} for more detail). Hovering the \faMousePointer{}~mouse pointer over each dot will display a short call stack summary while clicking on the dot with the \LMB{}~left mouse button will open a more detailed call stack information window (see section~\ref{callstackwindow}).

\subparagraph{Context switches}

The thick line right below the samples represents context switch data (see section~\ref{contextswitches}). We can see that the main thread, as displayed, starts in a suspended state, represented by the dotted region. Then it is woken up and starts execution of the \texttt{Update} zone. It is preempted amid the physics processing, which explains why there is an empty space between child zones. Then it is resumed again and continues execution into the \texttt{Render} zone, where it is preempted again, but for a shorter time. After rendering is done, the thread sleeps again, presumably waiting for the vertical blanking to indicate the next frame. Similar information is also available for the streaming thread.

Context switch regions are using the following color key:

\begin{itemize}
\item \emph{Green} -- Thread is running.
\item \emph{Red} -- Thread is waiting to be resumed by the scheduler. There are many reasons why a thread may be in the waiting state. Hovering the \faMousePointer{}~mouse pointer over the region will display more information. If sampling was performed, the profiler might display a wait stack. See section~\ref{waitstacks} for additional details.
\item \emph{Blue} -- Thread is waiting to be resumed and is migrating to another CPU core. This might have visible performance effects because low-level CPU caches are not shared between cores, which may result in additional cache misses. To avoid this problem, you may pin a thread to a specific core by setting its affinity.
\item \emph{Bronze} -- Thread has been placed in the scheduler's run queue and is about to be resumed.
\end{itemize}

Fiber work and yield states are presented in the same way as context switch regions.

\subparagraph{CPU data}

This label is only available if the profiler collected context switch data. It is split into two parts: a graph of CPU load by various threads running in the system and a per-core thread execution display.

The CPU load graph shows how much CPU resources were used at any given time during program execution. The green part of the graph represents threads belonging to the profiled application, and the gray part of the graph shows all other programs running in the system. Hovering the \faMousePointer{}~mouse pointer over the graph will display a list of threads running on the CPU at the given time.

Each line in the thread execution display represents a separate logical CPU thread. If CPU topology data is available (see section~\ref{cputopology}), package and core assignment will be displayed in brackets, in addition to numerical processor identifier (i.e. \texttt{[\emph{package}:\emph{core}] CPU \emph{thread}}). When a core is busy executing a thread, a zone will be drawn at the appropriate time. Zones are colored according to the following key:

\begin{itemize}
\item \emph{Bright color} -- or \emph{orange} if dynamic thread colors are disabled -- Thread tracked by the profiler.
\item \emph{Dark blue} -- Thread existing in the profiled application but not known to the profiler. This may include internal profiler threads, helper threads created by external libraries, etc.
\item \emph{Gray} -- Threads assigned to other programs running in the system.
\end{itemize}

When the \faMousePointer{}~mouse pointer is hovered over either the CPU data zone or the thread timeline label, Tracy will display a line connecting all zones associated with the selected thread. This can be used to quickly see how the thread migrated across the CPU cores.

Clicking the \LMB{}~left mouse button on a tracked thread will make it visible on the timeline if it was either hidden or collapsed before.

Careful examination of the data presented on this graph may allow you to determine areas where the profiled application was fighting for system resources with other programs (see section~\ref{checkenvironmentos}) or give you a hint to add more instrumentation macros.

\subparagraph{Locks}

Mutual exclusion zones are displayed in each thread that tries to acquire them. There are three color-coded kinds of lock event regions that may be displayed. Note that the contention regions are always displayed over the uncontented ones when the timeline view is zoomed out.

\begin{itemize}
\item \emph{Green region\footnote{This region type is disabled by default and needs to be enabled in options (section~\ref{options}).}} -- The lock is being held solely by one thread, and no other thread tries to access it. In the case of shared locks, multiple threads hold the read lock, but no thread requires a write lock.
\item \emph{Yellow region} -- The lock is being owned by this thread, and some other thread also wants to acquire the lock.
\item \emph{Red region} -- The thread wants to acquire the lock but is blocked by other thread or threads in case of a shared lock.
\end{itemize}

Hovering the \faMousePointer{}~mouse pointer over a lock timeline will highlight the lock in all threads to help read the lock behavior. Hovering the \faMousePointer{}~mouse pointer over a lock event will display important information, for example, a list of threads that are currently blocking or which are blocked by the lock. Clicking the \LMB{}~left mouse button on a lock event or a lock label will open the lock information window, as described in section~\ref{lockwindow}. Clicking the \MMB{}~middle mouse button on a lock event will zoom the view to the extent of the event.

\subparagraph{Plots}
\label{plots}

The numerical data values (figure~\ref{plot}) are plotted right below the zones and locks. Note that the minimum and maximum values currently displayed on the plot are visible on the screen, along with the y range of the plot and the number of drawn data points. The discrete data points are indicated with little rectangles. A filled rectangle indicates multiple data points.

\begin{figure}[h]
\centering\begin{tikzpicture}
[dot/.style={rectangle,draw,scale=0.5}];
\draw(0, -0.15) -- (0.2, -0.15) -- (0.1, -0.35) -- (0, -0.15);
\draw(0.25, 0) node[anchor=north west] {Queue size (y-range: 463, visible data points: 7)};
\draw[densely dotted] (0, -0.5) -- +(15, 0);
\draw(0, -0.5) node[anchor=north west] {731};
\draw(0, -3) node[anchor=south west] {268};
\draw[densely dotted] (0, -3) -- +(15, 0);

\draw(0, -2) -- (1, -2.3) node[dot]{} -- (1.2, -3) node[dot]{} -- (6, -1.2) node[dot]{} -- (7, -0.5) node[dot]{} -- (9, -2) node[dot]{} -- (15, -2.5);
\end{tikzpicture}
\caption{Plot display.}
\label{plot}
\end{figure}

When memory profiling (section~\ref{memoryprofiling}) is enabled, Tracy will automatically generate a \emph{\faMemory{}~Memory usage} plot, which has extended capabilities. For example, hovering over a data point (memory allocation event) will visually display the allocation duration. Clicking the \LMB{} left mouse button on the data point will open the memory allocation information window, which will show the duration of the allocation as long as the window is open.

Another plot that Tracy automatically provides is the \emph{\faTachometer*{}~CPU usage} plot, which represents the total system CPU usage percentage (it is not limited to the profiled application).

\subsubsection{Navigating the view}

Hovering the \faMousePointer{} mouse pointer over the timeline view will display a vertical line that you can use to line up events in multiple threads visually. Dragging the \LMB{} left mouse button will display the time measurement of the selected region.

The timeline view may be scrolled both vertically and horizontally by dragging the \RMB{} right mouse button. Note that only the zones, locks, and plots scroll vertically, while the time scale and frame sets always stay on the top.

You can zoom in and out the timeline view by using the \Scroll{}~mouse wheel. Pressing the \keys{\ctrl} key will make zooming more precise while pressing the \keys{\shift} key will make it faster. You can select a range to which you want to zoom in by dragging the \MMB{} middle mouse button. Dragging the \MMB{} middle mouse button while the \keys{\ctrl} key is pressed will zoom out.

It is also possible to navigate the timeline using the keyboard. The \keys{A} and \keys{D} keys scroll the view to the left and right, respectively. The \keys{W} and \keys{S} keys change the zoom level.

\subsection{Time ranges}
\label{timeranges}

Sometimes, you may want to specify a time range, such as limiting some statistics to a specific part of your program execution or marking interesting places.

To define a time range, drag the \LMB{}~left mouse button over the timeline view while holding the \keys{\ctrl} key. When the mouse key is released, the profiler will mark the selected time extent with a blue striped pattern, and it will display a context menu with the following options:

\begin{itemize}
\item \emph{\faSearch{}~Limit find zone time range} -- this will limit find zone results. See chapter~\ref{findzone} for more details.
\item \emph{\faSortAmountUp{}~Limit statistics time range} -- selecting this option will limit statistics results. See chapter~\ref{statistics} for more details.
\item \emph{\faHourglassHalf{}~Limit wait stacks time range} -- limits wait stacks results. Refer to chapter~\ref{waitstackswindow}.
\item \emph{\faMemory{}~Limit memory time range} -- limits memory results. Read more about this in chapter~\ref{memorywindow}.
\item \emph{\faStickyNote{}~Add annotation} -- use to annotate regions of interest, as described in chapter~\ref{annotatingtrace}.
\end{itemize}

Alternatively, you may specify the time range by clicking the \RMB{}~right mouse button on a zone or a frame. The resulting time extent will match the selected item.

To reduce clutter, time range regions are only displayed if the windows they affect are open or if the time range limits control window is open (section~\ref{timerangelimits}). You can access the time range limits window through the \emph{\faTools{} Tools} button on the control menu.

You can freely adjust each time range on the timeline by clicking the \LMB{}~left mouse button on the range's edge and dragging the mouse.

\subsubsection{Annotating the trace}
\label{annotatingtrace}

Tracy allows adding custom notes to the trace. For example, you may want to mark a region to ignore because the application was out-of-focus or a region where a new user was connecting to the game, which resulted in a frame drop that needs to be investigated.

Methods of specifying the annotation region are described in section~\ref{timeranges}. When a new annotation is added, a settings window is displayed (section~\ref{annotationsettings}), allowing you to enter a description.

Annotations are displayed on the timeline, as presented in figure~\ref{annotation}. Clicking on the circle next to the text description will open the annotation settings window, in which you can modify or remove the region. List of all annotations in the trace is available in the annotations list window described in section~\ref{annotationlist}, which is accessible through the \emph{\faTools{} Tools} button on the control menu.

\begin{figure}[h]
\centering\begin{tikzpicture}
\draw (0, 0.25) -- (0, 1) -- (5, 1) -- (5, 0.25);
\draw[dotted] (0, -0.2) -- (0, 0.25);
\draw[dotted] (5, -0.2) -- (5, 0.25);
\draw (0.25, 0.75) circle(0.15);
\draw (0.4, 0.7) node[anchor=west] {Description};
\end{tikzpicture}
\caption{Annotation region.}
\label{annotation}
\end{figure}

Please note that while the annotations persist between profiling sessions, they are not saved in the trace but in the user data files, as described in section~\ref{tracespecific}.

\subsection{Options menu}
\label{options}

In this window, you can set various trace-related options. For example, the timeline view might sometimes become overcrowded, in which case disabling the display of some profiling events can increase readability.

\begin{itemize}
\item \emph{\faExpand{} Draw empty labels} -- By default threads that don't have anything to display at the current zoom level are hidden. Enabling this option will show them anyway.
\item \emph{\faFlagCheckered{} Draw frame targets} -- If enabled, time regions in any frame from the currently selected frame set, which exceed the specified \emph{Target FPS} value will be marked with a red background on timeline view.
\begin{itemize}
\item \emph{Target FPS} -- Controls the option above, but also the frame bar colors in the frame time graph (section~\ref{frametimegraph}). The color range thresholds are presented in a line directly below.
\end{itemize}
\item \emph{\faHiking{} Draw context switches} -- Allows disabling context switch display in threads.
\begin{itemize}
\item \emph{\faMoon{} Darken inactive thread} -- If enabled, inactive regions in threads will be dimmed out.
\end{itemize}
\item \emph{\faSlidersH{} Draw CPU data} -- Per-CPU behavior graph can be disabled here.
\begin{itemize}
\item \emph{\faSignature{} Draw CPU usage graph} -- You can disable drawing of the CPU usage graph here.
\end{itemize}
\item \emph{\faEye{} Draw GPU zones} -- Allows disabling display of OpenGL/Vulkan/Direct3D/OpenCL zones. The \emph{GPU zones} drop-down allows disabling individual GPU contexts and setting CPU/GPU drift offsets of uncalibrated contexts (see section~\ref{gpuprofiling} for more information). The \emph{\faRobot~Auto} button automatically measures the GPU drift value\footnote{There is an assumption that drift is linear. Automated measurement calculates and removes change over time in delay-to-execution of GPU zones. Resulting value may still be incorrect.}.
\item \emph{\faMicrochip{} Draw CPU zones} -- Determines whether CPU zones are displayed.
\begin{itemize}
\item \emph{\faGhost{} Draw ghost zones} -- Controls if ghost zones should be displayed in threads which don't have any instrumented zones available.
\item \emph{\faPalette{} Zone colors} -- Zones with no user-set color may be colored according to the following schemes:
\begin{itemize}
\item \emph{Disabled} -- A constant color (blue) will be used.
\item \emph{Thread dynamic} -- Zones are colored according to a thread (identifier number) they belong to and depth level.
\item \emph{Source location dynamic} -- Zone color is determined by source location (function name) and depth level.
\end{itemize}
Enabling the \emph{Ignore custom} option will force usage of the selected zone coloring scheme, disregarding any colors set by the user in profiled code.
\item \emph{\faRulerHorizontal{} Zone name shortening} -- controls display behavior of long zone names, which don't fit inside a zone box:
\begin{itemize}
\item \emph{Disabled} -- Shortening of zone names is not performed and names are always displayed in full (e.g.\ \texttt{bool ns::container<float>::add(const float\&)}).
\item \emph{Minimal length} -- Always reduces zone name to minimal length, even if there is space available for a longer form (e.g.\ \texttt{add()}).
\item \emph{Only normalize} -- Only performs normalization of the zone name\footnote{The normalization process removes the function \texttt{const} qualifier, some common return type declarations and all function parameters and template arguments.}, but does not remove namespaces (e.g.\ \texttt{ns::container<>::add()}).
\item \emph{As needed} -- Name shortening steps will be performed only if there is no space to display a complete zone name, and only until the name fits available space, or shortening is no longer possible (e.g.\ \texttt{container<>::add()}).
\item \emph{As needed + normalize} -- Same as above, but zone name normalization will always be performed, even if the entire zone name fits in the space available.
\end{itemize}
Function names in the remaining places across the UI will be normalized unless this option is set to \emph{Disabled}.
\end{itemize}
\item \emph{\faLock{} Draw locks} -- Controls the display of locks. If the \emph{Only contended} option is selected, the profiler won't display the non-blocking regions of locks (see section~\ref{zoneslocksplots}). The \emph{Locks} drop-down allows disabling the display of locks on a per-lock basis. As a convenience, the list of locks is split into the single-threaded and multi-threaded (contended and uncontended) categories. Clicking the \RMB{}~right mouse button on a lock label opens the lock information window (section~\ref{lockwindow}).
\item \emph{\faSignature{} Draw plots} -- Allows disabling display of plots. Individual plots can be disabled in the \emph{Plots} drop-down.
\item \emph{\faRandom{} Visible threads} -- Here you can select which threads are visible on the timeline. You can change the display order of threads by dragging thread labels.
\item \emph{\faImages{} Visible frame sets} -- Frame set display can be enabled or disabled here. Note that disabled frame sets are still available for selection in the frame set selection drop-down (section~\ref{controlmenu}) but are marked with a dimmed font.
\end{itemize}

Disabling the display of some events is especially recommended when the profiler performance drops below acceptable levels for interactive usage.

\subsection{Messages window}
\label{messages}

In this window, you can see all the messages that were sent by the client application, as described in section~\ref{messagelog}. The window is split into four columns: \emph{time}, \emph{thread}, \emph{message} and \emph{call stack}. Hovering the \faMousePointer{}~mouse cursor over a message will highlight it on the timeline view. Clicking the \LMB{} left mouse button on a message will center the timeline view on the selected message.

The \emph{call stack} column is filled only if a call stack capture was requested, as described in section~\ref{collectingcallstacks}. A single entry consists of the \emph{\faAlignJustify{}~Show} button, which opens the call stack information window (chapter~\ref{callstackwindow}) and of abbreviated information about the call path.

If the \emph{\faImage{}~Show frame images} option is selected, hovering the \faMousePointer{}~mouse cursor over a message will show a tooltip containing frame image (see section~\ref{frameimages}) associated with a frame in which the message was issued, if available.

The message list will automatically scroll down to display the most recent message during live capture. You can disable this behavior by manually scrolling the message list up. The auto-scrolling feature will be enabled again when the view is scrolled down to display the last message.

You can filter the message list in the following ways:

\begin{itemize}
\item By the originating thread in the \emph{\faRandom{} Visible threads} drop-down.
\item By matching the message text to the expression in the \emph{\faFilter{}~Filter messages} entry field. Multiple filter expressions can be comma-separated (e.g. 'warn, info' will match messages containing strings 'warn' \emph{or} 'info'). You can exclude matches by preceding the term with a minus character (e.g., '-debug' will hide all messages containing the string 'debug').
\end{itemize}

\subsection{Statistics window}
\label{statistics}

Looking at the timeline view gives you a very localized outlook on things. However, sometimes you want to look at the general overview of the program's behavior. For example, you want to know which function takes the most of the application's execution time. The statistics window provides you with exactly that information.

If the trace capture was performed with call stack sampling enabled (as described in chapter~\ref{sampling}), you will be presented with an option to switch between \emph{\faSyringe{}~Instrumentation} and \emph{\faEyeDropper{}~Sampling} modes. If the profiler collected no sampling data, but it retrieved symbols, the second mode will be displayed as \emph{\faPuzzlePiece{}~Symbols}, enabling you to list available symbols.

If GPU zones were captured, you would also have the \emph{\faEye{}~GPU} option to view the GPU zones statistics.

\subsubsection{Instrumentation mode}

Here you will find a multi-column display of captured zones, which contains: the zone \emph{name} and \emph{location}, \emph{total time} spent in the zone, the \emph{count} of zone executions and the \emph{mean time spent in the zone per call}. You may sort the view according to the three displayed values.

In the \emph{~Timing} menu, the \emph{~With children} selection displays inclusive measurements, that is, containing execution time of zone's children. The \emph{~Self only} selection switches the measurement to exclusive, displaying just the time spent in the zone, subtracting the child calls. Finally, the \emph{~Non-reentrant} selection shows inclusive time but counts only the first appearance of a given zone on a thread's stack.

Clicking the \LMB{} left mouse button on a zone will open the individual zone statistics view in the find zone window (section~\ref{findzone}).

You can filter the displayed list of zones by matching the zone name to the expression in the \emph{\faFilter{}~Filter zones} entry field. Refer to section~\ref{messages} for a more detailed description of the expression syntax.

To limit the statistics to a specific time extent, you may enable the \emph{Limit range} option (chapter~\ref{timeranges}). The inclusion region will be marked with a red striped pattern. Note that a zone must be entirely inside the region to be counted. You can access more options through the \emph{\faRuler{}~Limits} button, which will open the time range limits window, described in section~\ref{timerangelimits}.

\subsubsection{Sampling mode}
\label{statisticssampling}

Data displayed in this mode is, in essence, very similar to the instrumentation one. Here you will find function names, their locations in source code, and time measurements. There are, however, some significant differences.

First and foremost, the presented information is constructed from many call stack samples, which represent real addresses in the application's binary code, mapped to the line numbers in the source files. This reverse mapping may not always be possible or could be erroneous. Furthermore, due to the nature of the sampling process, it is impossible to obtain exact time measurements. Instead, time values are guesstimated by multiplying the number of sample counts by mean time between two different samples.

The \emph{Name} column contains name of the function in which the sampling was done. Kernel-mode function samples are distinguished with the red color. If the \emph{\faSitemap{}~Inlines} option is enabled, functions which were inlined will be preceded with a '\faCaretRight{}' symbol and additionally display their parent function name in parenthesis. Otherwise, only non-inlined functions are listed, with a count of inlined functions in parenthesis. You may expand any entry containing an inlined function to display the corresponding functions list (some functions may be hidden if the \emph{\faPuzzlePiece{}~Show all} option is disabled due to lack of sampling data). Clicking on a function name will open the sample entry call stacks window (see chapter~\ref{sampleparents}). Note that if inclusive times are displayed, listed functions will be partially or completely coming from mid-stack frames, preventing, or limiting the capability to display parent call stacks.

The \emph{Location} column displays the corresponding source file name and line number. Depending on the \emph{Location} option selection, it can either show the function entry address or the instruction at which the sampling was performed. The \emph{Entry} mode points at the beginning of a non-inlined function or at the place where the compiler inserted an inlined function in its parent function. The \emph{Sample} mode is not useful for non-inlined functions, as it points to one randomly selected sampling point out of many that were captured. However, in the case of inlined functions, this random sampling point is within the inlined function body. Using these options in tandem lets you look at both the inlined function code and the place where it was inserted. If the \emph{Smart} location is selected, the profiler will display the entry point position for non-inlined functions and sample location for inlined functions. Selecting the \emph{\faAt{}~Address} option will instead print the symbol address.

The location data is complemented by the originating executable image name, contained in the \emph{Image} column.

The profiler may not find some function locations due to insufficient debugging data available on the client-side. To filter out such entries, use the \emph{\faEyeSlash{}~Hide unknown} option.

The \emph{Time} or \emph{Count} column (depending on the \emph{\faStopwatch{}~Show time} option selection) shows number of taken samples, either as a raw count, or in an easier to understand time format. Note that the percentage value of time is calculated relative to the wall-clock time. The percentage value of sample counts is relative to the total number of collected samples.

The last column, \emph{Code size}, displays the size of the symbol in the executable image of the program. Since inlined routines are directly embedded into other functions, their symbol size will be based on the parent symbol and displayed as 'less than'. In some cases, this data won't be available. If the symbol code has been retrieved\footnote{Symbols larger than 128~KB are not captured.} symbol size will be prepended with the \texttt{\faDatabase}~icon, and clicking the \RMB{}~right mouse button on the location column entry will open symbol view window (section~\ref{symbolview}).

Finally, the list can be filtered using the \emph{\faFilter{}~Filter symbols} entry field, just like in the instrumentation mode case. Additionally, you can also filter results by the originating image name of the symbol. You may disable the display of kernel symbols with the \emph{\faHatWizard{}~Include kernel} switch. The exclusive/inclusive time counting mode can be switched using the \emph{~Timing} menu (non-reentrant timing is not available in the Sampling view). Limiting the time range is also available but is restricted to self-time. If the \emph{\faPuzzlePiece{}~Show all} option is selected, the list will include not only the call stack samples but also all other symbols collected during the profiling process (this is enabled by default if no sampling was performed).

\subsubsection{GPU zones mode}

This is an analog of the instrumentation mode, but for the GPU zones. Note that the available options may be limited here.

\subsection{Find zone window}
\label{findzone}

The individual behavior of zones may be influenced by many factors, like CPU cache effects, access times amortized by the disk cache, thread context switching, etc. Moreover, sometimes the execution time depends on the internal data structures and their response to different inputs. In other words, it is hard to determine the actual performance characteristics by looking at any single zone.

Tracy gives you the ability to display an execution time histogram of all occurrences of a zone. On this view, you can see how the function behaves in general. You can inspect how various data inputs influence the execution time. You can filter the data to eventually drill down to the individual zone calls to see the environment in which they were called.

You start by entering a search query, which will be matched against known zone names (see section~\ref{markingzones} for information on the grouping of zone names). If the search found some results, you will be presented with a list of zones in the \emph{matched source locations} drop-down. The selected zone's graph is displayed on the \emph{histogram} drop-down, and also the matching zones are highlighted on the timeline view. Clicking the \RMB{} right mouse button on the source file location will open the source file view window (if applicable, see section~\ref{sourceview}).

An example histogram is presented in figure~\ref{findzonehistogram}. Here you can see that the majority of zone calls (by count) are clustered in the 300~\si{\nano\second} group, closely followed by the 10~\si{\micro\second} cluster. There are some outliers at the 1~and~10~\si{\milli\second} marks, which can be ignored on most occasions, as these are single occurrences.

\begin{figure}[h]
\centering\begin{tikzpicture}
\draw(0, 0) rectangle+(10, 3);
\draw (0, -0.1) -- +(0, -0.7);
\draw (0.6, -0.1) -- +(0, -0.1);
\draw (0.96, -0.1) -- +(0, -0.1);
\draw (1.2, -0.1) -- +(0, -0.1);
\draw (1.4, -0.1) -- +(0, -0.1);
\draw (1.56, -0.1) -- +(0, -0.1);
\draw (1.68, -0.1) -- +(0, -0.1);
\draw (1.8, -0.1) -- +(0, -0.1);
\draw (1.9, -0.1) -- +(0, -0.1);
\foreach \x in {2,4,6,8} {
\draw (\x+0, -0.1) -- +(0, -0.2);
\draw (\x+0.6, -0.1) -- +(0, -0.1);
\draw (\x+0.96, -0.1) -- +(0, -0.1);
\draw (\x+1.2, -0.1) -- +(0, -0.1);
\draw (\x+1.4, -0.1) -- +(0, -0.1);
\draw (\x+1.56, -0.1) -- +(0, -0.1);
\draw (\x+1.68, -0.1) -- +(0, -0.1);
\draw (\x+1.8, -0.1) -- +(0, -0.1);
\draw (\x+1.9, -0.1) -- +(0, -0.1); }
\draw (10, -0.1) -- +(0, -0.7);

\draw (-0.2, -0.8) node[anchor=north west] {100 \si{\nano\second}};
\draw (1.8, -0.3) node[anchor=north west] {1 \si{\micro\second}};
\draw (3.8, -0.3) node[anchor=north west] {10 \si{\micro\second}};
\draw (5.8, -0.3) node[anchor=north west] {100 \si{\micro\second}};
\draw (7.8, -0.3) node[anchor=north west] {1 \si{\milli\second}};
\draw (10.1, -0.8) node[anchor=north east] {10 \si{\milli\second}};

\draw (4.8, -0.81) node[anchor=north] {\faLongArrowAltLeft~10~\si{\milli\second}~\faLongArrowAltRight};

\draw[pattern=north east lines] (0,0) -- (0.5, 0.3) -- (1, 2.95) -- (1.4, 0.6) -- (2, 0.15) -- (3, 0.2) -- (3.7, 0.5) -- (4, 2.1) -- (4.3, 0.7) -- (5, 0.2) -- (6, 0);
\draw[pattern=north east lines] (7.8,0) -- (8, 0.15) -- (8.2, 0);
\draw[pattern=north east lines] (9.8,0) -- (9.9, 0.1) -- (10, 0);
\end{tikzpicture}
\caption{Zone execution time histogram. Note that the extreme time labels and time range indicator (middle time value) are displayed in a separate line.}
\label{findzonehistogram}
\end{figure}

Various data statistics about displayed data accompany the histogram, for example, the \emph{total time} of the displayed samples or the \emph{maximum number of counts} in histogram bins. The following options control how the data is presented:

\begin{itemize}
\item \emph{Log values} -- Switches between linear and logarithmic scale on the y~axis of the graph, representing the call counts\footnote{Or time, if the \emph{cumulate time} option is enabled.}.
\item \emph{Log time} -- Switches between linear and logarithmic scale on the x~axis of the graph, representing the time bins.
\item \emph{Cumulate time} -- Changes how the histogram bin values are calculated. By default, the vertical bars on the graph represent the \emph{call counts} of zones that fit in the given time bin. If this option is enabled, the bars represent the \emph{time spent} in the zones. For example, on the graph presented in figure~\ref{findzonehistogram} the 10~\si{\micro\second} cluster is the dominating one, if we look at the time spent in the zone, even if the 300~\si{\nano\second} cluster has a greater number of call counts.
\item \emph{Self time} -- Removes children time from the analyzed zones, which results in displaying only the time spent in the zone itself (or in non-instrumented function calls). It cannot be selected when \emph{Running time} is active.
\item \emph{Running time} -- Removes time when zone's thread execution was suspended by the operating system due to preemption by other threads, waiting for system resources, lock contention, etc. Available only when the profiler performed context switch capture (section~\ref{contextswitches}). It cannot be selected when \emph{Self time} is active.
\item \emph{Minimum values in bin} -- Excludes display of bins that do not hold enough values at both ends of the time range. Increasing this parameter will eliminate outliers, allowing us to concentrate on the interesting part of the graph.
\end{itemize}

You can drag the \LMB{} left mouse button over the histogram to select a time range that you want to look at closely. This will display the data in the histogram info section, and it will also filter zones shown in the \emph{found zones} section. This is quite useful if you actually want to look at the outliers, i.e.,\ where did they originate from, what the program was doing at the moment, etc\footnote{More often than not you will find out, that the application was just starting, or access to a cold file was required and there's not much you can do to optimize that particular case.}. You can reset the selection range by pressing the \RMB{} right mouse button on the histogram.

The \emph{found zones} section displays the individual zones grouped according to the following criteria:

\begin{itemize}
\item \emph{Thread} -- In this mode you can see which threads were executing the zone.
\item \emph{User text} -- Splits the zones according to the custom user text (see section~\ref{markingzones}).
\item \emph{Zone name} -- Groups zones by the name set on a per-call basis (see section~\ref{markingzones}).
\item \emph{Call stacks} -- Zones are grouped by the originating call stack (see section~\ref{collectingcallstacks}). Note that two call stacks may sometimes appear identical, even if they are not, due to an easily overlooked difference in the source line numbers.
\item \emph{Parent} -- Groups zones according to the parent zone. This mode relies on the zone hierarchy and \emph{not} on the call stack information.
\item \emph{No grouping} -- Disables zone grouping. It may be useful when you want to see zones in order as they appear.
\end{itemize}

You may sort each group according to the \emph{order} in which it appeared, the call \emph{count}, the total \emph{time} spent in the group, or the \emph{mean time per call}. Expanding the group view will display individual occurrences of the zone, which can be sorted by application's time, execution time, or zone's name. Clicking the \LMB{} left mouse button on a zone will open the zone information window (section~\ref{zoneinfo}). Clicking the \MMB{} middle mouse button on a zone will zoom the timeline view to the zone's extent.

Clicking the \LMB{} left mouse button on the group name will highlight the group time data on the histogram (figure~\ref{findzonehistogramgroup}). This function provides a quick insight into the impact of the originating thread or input data on the zone performance. Clicking on the \emph{\faBackspace~Clear} button will reset the group selection. If the grouping mode is set to \emph{Parent} option, clicking the \MMB{}~middle mouse button on the parent zone group will switch the find zone view to display the selected zone.

\begin{figure}[h]
\centering\begin{tikzpicture}
\draw(0, 0) rectangle+(10, 3);
\foreach \x in {0,2,4,6,8} {
\draw (\x+0, -0.1) -- +(0, -0.2);
\draw (\x+0.6, -0.1) -- +(0, -0.1);
\draw (\x+0.96, -0.1) -- +(0, -0.1);
\draw (\x+1.2, -0.1) -- +(0, -0.1);
\draw (\x+1.4, -0.1) -- +(0, -0.1);
\draw (\x+1.56, -0.1) -- +(0, -0.1);
\draw (\x+1.68, -0.1) -- +(0, -0.1);
\draw (\x+1.8, -0.1) -- +(0, -0.1);
\draw (\x+1.9, -0.1) -- +(0, -0.1); }
\draw (10, -0.1) -- +(0, -0.2);

\draw (-0.2, -0.3) node[anchor=north west] {100 \si{\nano\second}};
\draw (1.8, -0.3) node[anchor=north west] {1 \si{\micro\second}};
\draw (3.8, -0.3) node[anchor=north west] {10 \si{\micro\second}};
\draw (5.8, -0.3) node[anchor=north west] {100 \si{\micro\second}};
\draw (7.8, -0.3) node[anchor=north west] {1 \si{\milli\second}};
\draw (9.8, -0.3) node[anchor=north west] {10 \si{\milli\second}};

\draw[pattern=north east lines] (0,0) -- (0.5, 0.3) -- (1, 2.95) -- (1.4, 0.6) -- (2, 0.15) -- (3, 0.2) -- (3.7, 0.5) -- (4, 2.1) -- (4.3, 0.7) -- (5, 0.2) -- (6, 0);
\draw[pattern=north east lines] (7.8,0) -- (8, 0.15) -- (8.2, 0);
\draw[pattern=north east lines] (9.8,0) -- (9.9, 0.1) -- (10, 0);

\draw[pattern=north west lines] (3.2, 0) -- (3.75, 0.3) -- (3.95, 1.4) -- (4.2, 0);
\end{tikzpicture}
\caption{Zone execution time histogram with a group highlighted.}
\label{findzonehistogramgroup}
\end{figure}

The call stack grouping mode has a different way of listing groups. Here only one group is displayed at any time due to the need to display the call stack frames. You can switch between call stack groups by using the~\faCaretLeft{}~and~\faCaretRight{} buttons. You can select the group by clicking on the~\emph{\faCheck{}~Select} button. You can open the call stack window (section~\ref{callstackwindow}) by pressing the~\emph{\faAlignJustify{}~Call~stack} button.

Tracy displays a variety of statistical values regarding the selected function: mean (average value), median (middle value), mode (most common value, quantized using histogram bins), and \textsigma{} (standard deviation). The mean and median zone times are also displayed on the histogram as red (mean) and blue (median) vertical bars. Additional bars will indicate the mean group time (orange) and median group time (green). You can disable the drawing of either set of markers by clicking on the check-box next to the color legend.

Hovering the \faMousePointer{}~mouse cursor over a zone on the timeline, which is currently selected in the find zone window, will display a pulsing vertical bar on the histogram, highlighting the bin to which the hovered zone has been assigned. In addition, it will also highlight zone entry on the zone list.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bclampe
]{Keyboard shortcut}
You may press \keys{\ctrl + F} to open or focus the find zone window and set the keyboard input on the search box.
\end{bclogo}

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcattention
]{Caveats}
When using the execution times histogram, you must know the hardware peculiarities. Read section~\ref{checkenvironmentcpu} for more detail.
\end{bclogo}

\subsubsection{Timeline interaction}

The profiler will highlight matching zones on the timeline display when the zone statistics are displayed in the find zone menu. Highlight colors match the histogram display. A bright blue highlight indicates that a zone is in the optional selection range, while the yellow highlight is used for the rest of the zones.

\subsubsection{Frame time graph interaction}
\label{frametimefindzone}

The frame time graph (section~\ref{frametimegraph}) behavior is altered when a zone is displayed in the find zone window and the \emph{Show zone time in frames} option is selected. An accumulated zone execution time is shown instead of coloring the frame bars according to the frame time targets.

Each bar is drawn in gray color, with the white part accounting for the zone time. If the execution time is greater than the frame time (this is possible if more than one thread was executing the same zone), the overflow will be displayed using red color.

Enabling \emph{Self time} option affects the displayed values, but \emph{Running time} does not.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcattention
]{Caveats}
The profiler might not calculate the displayed data correctly, and it may not include some zones in the reported times.
\end{bclogo}

\subsubsection{Limiting zone time range}

If the \emph{Limit range} option is selected, the profiler will include only the zones within the specified time range (chapter~\ref{timeranges}) in the data. The inclusion region will be marked with a green striped pattern. Note that a zone must be entirely inside the region to be counted. You can access more options through the \emph{\faRuler{}~Limits} button, which will open the time range limits window, described in section~\ref{timerangelimits}.

\subsubsection{Zone samples}

If sampling data has been captured (see section~\ref{sampling}), an additional expandable \emph{\faEyeDropper{}~Samples} section will be displayed. This section contains only the sample data attributed to the displayed zone. Looking at this list may give you additional insight into what is happening within the zone. Refer to section~\ref{statisticssampling} for more information about this view.

You can further narrow down the list of samples by selecting a time range on the histogram or by choosing a group in the \emph{Found zones} section. However, do note that the random nature of sampling makes it highly unlikely that short-lived zones (i.e., left part of the histogram) will have any sample data collected.

\subsection{Compare traces window}
\label{compare}

Comparing the performance impact of the optimization work is not an easy thing to do. Benchmarking is often inconclusive, if even possible, in the case of interactive applications, where the benchmarked function might not have a visible impact on frame render time. Furthermore, doing isolated micro-benchmarks loses the application's execution environment, in which many different parts compete for limited system resources.

Tracy solves this problem by providing a compare traces functionality, very similar to the find zone window, described in section~\ref{findzone}. You can compare traces either by zone or frame timing data.

You would begin your work by recording a reference trace that represents the usual behavior of the program. Then, after the optimization of the code is completed, you record another trace, doing roughly what you did for the reference one. Finally, having the optimized trace open, you select the \emph{\faFolderOpen{}~Open second trace} option in the compare traces window and load the reference trace.

Now things start to get familiar. You search for a zone, similarly like in the find zone window, choose the one you want in the \emph{matched source locations} drop-down, and then you look at the histogram\footnote{When comparing frame times you are presented with a list of available frame sets, without the search box.}. This time there are two overlaid graphs, one representing the current trace and the second one representing the external (reference) trace (figure~\ref{comparehistogram}). You can easily see how the performance characteristics of the zone were affected by your modifications.

\begin{figure}[h]
\centering\begin{tikzpicture}
\draw(0, 0) rectangle+(10, 3);
\foreach \x in {0,2,4,6,8} {
\draw (\x+0, -0.1) -- +(0, -0.2);
\draw (\x+0.6, -0.1) -- +(0, -0.1);
\draw (\x+0.96, -0.1) -- +(0, -0.1);
\draw (\x+1.2, -0.1) -- +(0, -0.1);
\draw (\x+1.4, -0.1) -- +(0, -0.1);
\draw (\x+1.56, -0.1) -- +(0, -0.1);
\draw (\x+1.68, -0.1) -- +(0, -0.1);
\draw (\x+1.8, -0.1) -- +(0, -0.1);
\draw (\x+1.9, -0.1) -- +(0, -0.1); }
\draw (10, -0.1) -- +(0, -0.2);

\draw (-0.2, -0.3) node[anchor=north west] {100 \si{\nano\second}};
\draw (1.8, -0.3) node[anchor=north west] {1 \si{\micro\second}};
\draw (3.8, -0.3) node[anchor=north west] {10 \si{\micro\second}};
\draw (5.8, -0.3) node[anchor=north west] {100 \si{\micro\second}};
\draw (7.8, -0.3) node[anchor=north west] {1 \si{\milli\second}};
\draw (9.8, -0.3) node[anchor=north west] {10 \si{\milli\second}};

\draw[pattern=north east lines] (0,0) -- (0.5, 0.3) -- (1, 2.95) -- (1.4, 1) -- (2, 0.5) -- (7, 0);
\draw[pattern=north west lines] (0.5,0) -- (1, 0.4) -- (1.7, 2.8) -- (2.1, 1.1) -- (2.7, 0.6) -- (5, 0.2) -- (10, 0);
\end{tikzpicture}
\caption{Compare traces histogram.}
\label{comparehistogram}
\end{figure}

Note that the traces are color and symbol-coded. The current trace is marked by a yellow \faLemon{} symbol, and the external one is marked by a red \faGem{} symbol.

When searching for source locations it's not uncommon to match more than one zone (for example a search for \texttt{Draw} may result in \texttt{DrawCircle} and \texttt{DrawRectangle} matches). Typically you wouldn't want to compare execution profiles of two unrelated functions, which is prevented by the \emph{link selection} option, which ensures that when you choose a source location in one trace, the corresponding one is also selected in the second trace. Be aware that this may still result in a mismatch, for example, if you have overloaded functions. In such a case, you will need to select the appropriate function in the other trace manually.

It may be difficult, if not impossible, to perform identical runs of a program. This means that the number of collected zones may differ in both traces, influencing the displayed results. To fix this problem, enable the \emph{Normalize values} option, which will adjust the displayed results as if both traces had the same number of recorded zones.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bclampe
]{Trace descriptions}
Set custom trace descriptions (see section~\ref{traceinfo}) to easily differentiate the two loaded traces. If no trace description is set, the name of the profiled program will be displayed along with the capture time.
\end{bclogo}

\subsubsection{Source files diff}

To see what changes were made in the source code between the two compared traces, select the \emph{Source diff} compare mode. This will display a list of deleted, added, and changed files. By default, the difference is calculated from the older trace to the newer one. You can reverse this by clicking on the \emph{Switch} button.

Please note that changes will be registered only if the file has the same name and location in both traces. Tracy does not resolve file renames or moves.

\subsection{Memory window}
\label{memorywindow}

You can view the data gathered by profiling memory usage (section~\ref{memoryprofiling}) in the memory window. If the profiler tracked more than one memory pool during the capture, you would be able to select which collection you want to look at, using the \emph{\faArchive{}~Memory pool} selection box.

The top row contains statistics, such as \emph{total allocations} count, number of \emph{active allocations}, current \emph{memory usage} and process \emph{memory span}\footnote{Memory span describes the address space consumed by the program. It is calculated as a difference between the maximum and minimum observed in-use memory address.}.

The lists of captured memory allocations are displayed in a common multi-column format through the profiler. The first column specifies the memory address of an allocation or an address and an offset if the address is not at the start of the allocation. Clicking the \LMB{} left mouse button on an address will open the memory allocation information window\footnote{While the allocation information window is opened, the address will be highlighted on the list.} (see section~\ref{memallocinfo}). Clicking the \MMB{}~middle mouse button on an address will zoom the timeline view to memory allocation's range. The next column contains the allocation size.

The allocation's timing data is contained in two columns: \emph{appeared at} and \emph{duration}. Clicking the \LMB{}~left mouse button on the first one will center the timeline view at the beginning of allocation, and likewise, clicking on the second one will center the timeline view at the end of allocation. Note that allocations that have not yet been freed will have their duration displayed in green color.

The memory event location in the code is displayed in the last four columns. The \emph{thread} column contains the thread where the allocation was made and freed (if applicable), or an \emph{alloc / free} pair of the threads if it was allocated in one thread and freed in another. The \emph{zone alloc} contains the zone in which the allocation was performed\footnote{The actual allocation is typically a couple functions deeper in the call stack.}, or \texttt{-} if there was no active zone in the given thread at the time of allocation. Clicking the \LMB{}~left mouse button on the zone name will open the zone information window (section~\ref{zoneinfo}). Similarly, the \emph{zone free} column displays the zone which freed the allocation, which may be colored yellow, if it is the same zone that did the allocation. Alternatively, if the zone has not yet been freed, a green \emph{active} text is displayed. The last column contains the \emph{alloc} and \emph{free} call stack buttons, or their placeholders, if no call stack is available (see section~\ref{collectingcallstacks} for more information). Clicking on either of the buttons will open the call stack window (section~\ref{callstackwindow}). Note that the call stack buttons that match the information window will be highlighted.

The memory window is split into the following sections:

\subsubsection{Allocations}

The \emph{\faAt{} Allocations} pane allows you to search for the specified address usage during the whole lifetime of the program. All recorded memory allocations that match the query will be displayed on a list.

\subsubsection{Active allocations}

The \emph{\faHeartbeat{} Active allocations} pane displays a list of currently active memory allocations and their total memory usage. Here, you can see where your program allocated memory it is now using. If the application has already exited, this becomes a list of leaked memory.

\subsubsection{Memory map}

On the \emph{\faMap{} Memory map} pane, you can see the graphical representation of your program's address space. Active allocations are displayed as green lines, while the freed memory is red. The brightness of the color indicates how much time has passed since the last memory event at the given location -- the most recent events are the most vibrant.

This view may help assess the general memory behavior of the application or in debugging the problems resulting from address space fragmentation.

\subsubsection{Bottom-up call stack tree}
\label{callstacktree}

The \emph{\faTree{}~Bottom-up call stack tree} pane is only available, if the memory events were collecting the call stack data (section~\ref{collectingcallstacks}). In this view, you are presented with a tree of memory allocations, starting at the call stack entry point and going up to the allocation's pinpointed place. Each tree level is sorted according to the number of bytes allocated in the given branch.

Each tree node consists of the function name, the source file location, and the memory allocation data. The memory allocation data is either yellow \emph{inclusive} events count (allocations performed by children) or the cyan \emph{exclusive} events count (allocations that took place in the node)\footnote{Due to the way call stacks work, there is no possibility for an entry to have both inclusive and exclusive counts, in an adequately instrumented program.}. Two values are counted: total memory size and number of allocations.

The \emph{Group by function name} option controls how tree nodes are grouped. If it is disabled, the grouping is performed at a machine instruction-level granularity. This may result in a very verbose output, but the displayed source locations are precise. To make the tree more readable, you may opt to perform grouping at the function name level, which will result in less valid source file locations, as multiple entries are collapsed into one.

Enabling the \emph{Only active allocations} option will limit the call stack tree only to display active allocations. Enabling \emph{Only inactive allocations} option will have similar effect for inactive allocations. Both are mutually exclusive, enabling one disables the other. Displaing inactive allocations, when combined with \emph{Limit range}, will show short lived allocatios highlighting potentially unwanted behavior in the code.

Clicking the \RMB{}~right mouse button on the function name will open the allocations list window (see section \ref{alloclist}), which lists all the allocations included at the current call stack tree level. Likewise, clicking the \RMB{}~right mouse button on the source file location will open the source file view window (if applicable, see section~\ref{sourceview}).

Some function names may be too long to correctly display, with the events count data at the end. In such cases, you may press the \emph{control} button, which will display the events count tooltip.

\subsubsection{Top-down call stack tree}

This pane is identical in functionality to the \emph{Bottom-up call stack tree}, but the call stack order is reversed when the tree is built. This means that the tree starts at the memory allocation functions and goes down to the call stack entry point.

\subsubsection{Looking back at the memory history}

By default, the memory window displays the memory data at the current point of program execution. It is, however, possible to view the historical data by enabling the \emph{\faRuler{}~Limits} option. The profiler will consider only the memory events within the time range in the displayed results. See section~\ref{timerangelimits} for more information.

\subsection{Allocations list window}
\label{alloclist}

This window displays the list of allocations included at the selected call stack tree level (see section~\ref{memorywindow} and \ref{callstacktree}).

\subsection{Memory allocation information window}
\label{memallocinfo}

The information about the selected memory allocation is displayed in this window. It lists the allocation's address and size, along with the time, thread, and zone data of the allocation and free events. Clicking the \emph{\faMicroscope{}~Zoom to allocation} button will zoom the timeline view to the allocation's extent.

\subsection{Trace information window}
\label{traceinfo}

This window contains information about the current trace: captured program name, time of the capture, profiler version which performed the capture, and a custom trace description, which you can fill in.

Open the \emph{Trace statistics} section to see information about the trace, such as achieved timer resolution, number of captured zones, lock events, plot data points, memory allocations, etc.

There's also a section containing the selected frame set timing statistics and histogram\footnote{See section~\ref{findzone} for a description of the histogram. Note that there are subtle differences in the available functionality.}. As a convenience, you can switch the active frame set here and limit the displayed frame statistics to the frame range visible on the screen.

If \emph{CPU topology} data is available (see section~\ref{cputopology}), you will be able to view the package, core, and thread hierarchy.

The \emph{Source location substitutions} section allows adapting the source file paths, as captured by the profiler, to the actual on-disk locations\footnote{This does not affect source files cached during the profiling run.}. You can create a new substitution by clicking the \emph{Add new substitution} button. This will add a new entry, with input fields for ECMAScript-conforming regular expression pattern and its corresponding replacement string. You can quickly test the outcome of substitutions in the \emph{example source location} input field, which will be transformed and displayed below, as \emph{result}.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bclampe
]{Quick example}
Let's say we have an Unix-based operating system with program sources in \texttt{/home/user/program/src/} directory. We have also performed a capture of an application running under Windows, with sources in \texttt{C:\textbackslash{}Users\textbackslash{}user\textbackslash{}Desktop\textbackslash{}program\textbackslash{}src} directory. The source locations don't match, and the profiler can't access the source files on our disk. We can fix that by adding two substitution patterns:

\begin{itemize}
\item \texttt{\^{}C:\textbackslash{}\textbackslash{}Users\textbackslash{}\textbackslash{}user\textbackslash{}\textbackslash{}Desktop} \hspace{1em}\textrightarrow\hspace{1em} \texttt{/home/user}
\item \texttt{\textbackslash{}\textbackslash{}} \hspace{1em}\textrightarrow\hspace{1em} \texttt{/}
\end{itemize}
\end{bclogo}

In this window, you can view the information about the machine on which the profiled application was running. This includes the operating system, used compiler, CPU name, total available RAM, etc. In addition, if application information was provided (see section~\ref{appinfo}), it will also be displayed here.

If an application should crash during profiling (section~\ref{crashhandling}), the profiler will display the crash information in this window. It provides you information about the thread that has crashed, the crash reason, and the crash call stack (section~\ref{callstackwindow}).

\subsection{Zone information window}
\label{zoneinfo}

The zone information window displays detailed information about a single zone. There can be only one zone information window open at any time. While the window is open, the profiler will highlight the zone on the timeline view with a green outline. The following data is presented:

\begin{itemize}
\item Basic source location information: function name, source file location, and the thread name.
\item Timing information.
\item If the profiler performed context switch capture (section~\ref{contextswitches}) and a thread was suspended during zone execution, a list of wait regions will be displayed, with complete information about the timing, CPU migrations, and wait reasons. If CPU topology data is available (section~\ref{cputopology}), the profiler will mark zone migrations across cores with 'C' and migrations across packages -- with 'P.' In some cases, context switch data might be incomplete\footnote{For example, when capture is ongoing and context switch information has not yet been received.}, in which case a warning message will be displayed.
\item Memory events list, both summarized and a list of individual allocation/free events (see section~\ref{memorywindow} for more information on the memory events list).
\item List of messages that the profiler logged in the zone's scope. If the \emph{exclude children} option is disabled, messages emitted in child zones will also be included.
\item Zone trace, taking into account the zone tree and call stack information (section~\ref{collectingcallstacks}), trying to reconstruct a combined zone + call stack trace\footnote{Reconstruction is only possible if all zones have complete call stack capture data available. In the case where that's not available, an \emph{unknown frames} entry will be present.}. Captured zones are displayed as standard text, while not instrumented functions are dimmed. Hovering the \faMousePointer{}~mouse pointer over a zone will highlight it on the timeline view with a red outline. Clicking the \LMB{}~left mouse button on a zone will switch the zone info window to that zone. Clicking the \MMB{}~middle mouse button on a zone will zoom the timeline view to the zone's extent. Clicking the \RMB{}~right mouse button on a source file location will open the source file view window (if applicable, see section~\ref{sourceview}).
\item Child zones list, showing how the current zone's execution time was used. Zones on this list can be grouped according to their source location. Each group can be expanded to show individual entries. All the controls from the zone trace are also available here.
\item Time distribution in child zones, which expands the information provided in the child zones list by processing \emph{all} zone children (including multiple levels of grandchildren). This results in a statistical list of zones that were really doing the work in the current zone's time span. If a group of zones is selected on this list, the find zone window (section~\ref{findzone}) will open, with a time range limited to show only the children of the current zone.
\end{itemize}

The zone information window has the following controls available:

\begin{itemize}
\item \emph{\faMicroscope{} Zoom to zone} -- Zooms the timeline view to the zone's extent.
\item \emph{\faArrowUp{} Go to parent} -- Switches the zone information window to display current zone's parent zone (if available).
\item \emph{\faChartBar{} Statistics} -- Displays the zone general performance characteristics in the find zone window (section~\ref{findzone}).
\item \emph{\faAlignJustify{} Call stack} -- Views the current zone's call stack in the call stack window (section~\ref{callstackwindow}). The button will be highlighted if the call stack window shows the zone's call stack. Only available if zone had captured call stack data (section~\ref{collectingcallstacks}).
\item \emph{\faFile*{} Source} -- Display source file view window with the zone source code (only available if applicable, see section~\ref{sourceview}). The button will be highlighted if the source file is displayed (but the focused source line might be different).
\item \emph{\faArrowLeft{} Go back} -- Returns to the previously viewed zone. The viewing history is lost when the zone information window is closed or when the type of displayed zone changes (from CPU to GPU or vice versa).
\end{itemize}

Clicking on the \emph{\faClipboard{}~Copy to clipboard} buttons will copy the appropriate data to the clipboard.

\subsection{Call stack window}
\label{callstackwindow}

This window shows the frames contained in the selected call stack. Each frame is described by a function name, source file location, and originating image\footnote{Executable images are called \emph{modules} by Microsoft.} name. Function frames originating from the kernel are marked with a red color. Clicking the \LMB{}~left mouse button on either the function name of source file location will copy the name to the clipboard. Clicking the \RMB{}~right mouse button on the source file location will open the source file view window (if applicable, see section~\ref{sourceview}).

A single stack frame may have multiple function call places associated with it. This happens in the case of inlined function calls. Such entries will be displayed in the call stack window, with \emph{inline} in place of frame number\footnote{Or '\faCaretRight{}'~icon in case of call stack tooltips.}.

Stack frame location may be displayed in the following number of ways, depending on the \emph{\faAt{}~Frame location} option selection:

\begin{itemize}
\item \emph{Source code} -- displays source file and line number associated with the frame.
\item \emph{Entry point} -- source code at the beginning of the function containing selected frame, or function call place in case of inline frames.
\item \emph{Return address} -- shows return address, which you may use to pinpoint the exact instruction in the disassembly.
\item \emph{Symbol address} -- displays begin address of the function containing the frame address.
\end{itemize}

In some cases, it may not be possible to decode stack frame addresses correctly. Such frames will be presented with a dimmed '\texttt{[ntdll.dll]}' name of the image containing the frame address, or simply '\texttt{[unknown]}' if the profiler cannot retrieve even this information. Additionally, '\texttt{[kernel]}' is used to indicate unknown stack frames within the operating system's internal routines.

If the displayed call stack is a sampled call stack (chapter~\ref{sampling}), an additional button will be available, \emph{\faDoorOpen{}~Global entry statistics}. Clicking it will open the sample entry call stacks window (chapter~\ref{sampleparents}) for the current call stack.

Clicking on the \emph{\faClipboard{}~Copy to clipboard} button will copy call stack to the clipboard.

\subsubsection{Reading call stacks}
\label{readingcallstacks}

You need to take special care when reading call stacks. Contrary to their name, call stacks do not show \emph{function call stacks}, but rather \emph{function return stacks}. This might not be very clear at first, but this is how programs do work. Consider the following source code:

\begin{lstlisting}
int main()
{
    auto app = std::make_unique<Application>();
    app->Run();
    app.reset();
}
\end{lstlisting}

Let's say you are looking at the call stack of some function called within \texttt{Application::Run}. This is the result you might get:

\begin{lstlisting}
0. @\ldots@
1. @\ldots@
2. Application::Run
3. std::unique_ptr<Application>::reset
4. main
\end{lstlisting}

At the first glance it may look like \texttt{unique\_ptr::reset} was the \emph{call site} of the \texttt{Application::Run}, which would make no sense, but this is not the case here. When you remember these are the \emph{function return points}, it becomes much more clear what is happening. As an optimization, \texttt{Application::Run} is returning directly into \texttt{unique\_ptr::reset}, skipping the return to \texttt{main} and an unnecessary \texttt{reset} function call.

Moreover, the linker may determine in some rare cases that any two functions in your program are identical\footnote{For example, if all they do is zero-initialize a region of memory. As some constructors would do.}. As a result, only one copy of the binary code will be provided in the executable for both functions to share. While this optimization produces more compact programs, it also means that there's no way to distinguish the two functions apart in the resulting machine code. In effect, some call stacks may look nonsensical until you perform a small investigation.

\subsection{Sample entry call stacks window}
\label{sampleparents}

This window displays statistical information about the selected symbol. All sampled call stacks (chapter~\ref{sampling}) leading to the symbol are counted and displayed in descending order. You can choose the displayed call stack using the \emph{entry call stack} controls, which also display time spent in the selected call stack. Alternatively, sample counts may be shown by disabling the \emph{\faStopwatch{}~Show time} option, which is described in more detail in chapter~\ref{statisticssampling}.

The layout of frame list and the \emph{\faAt{}~Frame location} option selection is similar to the call stack window, described in chapter~\ref{callstackwindow}.

\subsection{Source view window}
\label{sourceview}

This window can operate in one of the two modes. The first one is quite simple, just showing the source code associated with a source file. The second one, which is used if symbol context is available, is considerably more feature-rich.

\subsubsection{Source file view}

In source view mode, you can view the source code of the profiled application to take a quick glance at the context of the function behavior you are analyzing. The profiler will highlight the selected line (for example, a location of a profiling zone) both in the source code listing and on the scroll bar.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Important}
To display source files, Tracy has to gain access to them somehow. Since having the source code is not needed for the profiled application to run, this can be problematic in some cases. The source files search order is as follows:

\begin{enumerate}
\item Discovery is performed on the server side. Found files are cached in the trace. \emph{This is appropriate when the client and the server run on the same machine or if you're deploying your application to the target device and then run the profiler on the same workstation.}
\item If not found, discovery is performed on the client-side. Found files are cached in the trace. \emph{This is appropriate when you are developing your code on another machine, for example, you may be working on a dev-board through an SSH connection.}
\item If not found, Tracy will try to open source files that you might have on your disk later on. The profiler won't store these files in the trace. You may provide custom file path substitution rules to redirect this search to the right place (see section~\ref{traceinfo}).
\end{enumerate}

Note that the discovery process not only looks for a file on the disk but it also checks its time stamp and validates it against the executable image timestamp or, if it's not available, the time of the performed capture. This will prevent the use of newer source files (i.e., were changed) than the program you're profiling.

Nevertheless, \textbf{the displayed source files might still not reflect the code that you profiled!} It is up to you to verify that you don't have a modified version of the code with regards to the trace.
\end{bclogo}

\subsubsection{Symbol view}
\label{symbolview}

A much more capable symbol view mode is available if the inspected source location has an associated symbol context (i.e., if it comes from a call stack capture, from call stack sampling, etc.). A symbol is a unit of machine code, basically a callable function. It may be generated using multiple source files and may consist of numerous inlined functions. A list of all captured symbols is available in the statistics window, as described in chapter~\ref{statisticssampling}.

The header of symbol view window contains a name of the selected \emph{\faPuzzlePiece{}~symbol}, a list of \emph{\faSitemap{}~functions} that contribute to the symbol, and information such as count of probed \emph{\faEyeDropper{}~Samples}.

Additionally, you may use the \emph{Mode} selector to decide what content should be displayed in the panels below:

\begin{itemize}
\item \emph{Source} -- only the source code will be displayed.
\item \emph{Assembly} -- only the machine code disassembly will be shown.
\item \emph{Both} -- selects combined mode, in which source code and disassembly will be listed next to each other.
\end{itemize}

Some modes may be unavailable in some circumstances (missing or outdated source files, lack of machine code). In case the \emph{Assembly} mode is unavailable, this might be due to the \texttt{capstone} disassembly engine failing to disassemble the machine instructions. See section~\ref{buildingserver} for more information.

\paragraph{Source mode}

This is pretty much the source file view window, but with the ability to select one of the source files that the compiler used to build the symbol. Additionally, each source file line that produced machine code in the symbol will show a count of associated assembly instructions, displayed with an '\texttt{@}' prefix, and will be marked with grey color on the scroll bar. Due to how optimizing compilers work, some lines may seemingly not produce any machine code, for example, because iterating a loop counter index might have been reduced to advancing a data pointer. Some other lines may have a disproportionate amount of associated instructions, e.g., when the compiler applied a loop unrolling optimization. This varies from case to case and from compiler to compiler.

The \emph{Propagate inlines} option, available when sample data is present, will enable propagation of the instruction costs down the local call stack. For example, suppose a base function in the symbol issues a call to an inlined function (which may not be readily visible due to being contained in another source file). In that case, any cost attributed to the inlined function will be visible in the base function. Because the cost information is added to all the entries in the local call stacks, it is possible to see seemingly nonsense total cost values when this feature is enabled. To quickly toggle this on or off, you may also press the \keys{X} key.

\paragraph{Assembly mode}

This mode shows the disassembly of the symbol machine code. If only one inline function is selected through the \emph{\faSitemap{}~Function} selector, assembly instructions outside of this function will be dimmed out. Each assembly instruction is displayed listed with its location in the program memory during execution. If the \emph{\faSearchLocation{}~Relative address} option is selected, the profiler will print an offset from the symbol beginning instead. Clicking the \LMB{}~left mouse button on the address/offset will switch to counting line numbers, using the selected one as the origin (i.e., zero value). Line numbers are displayed inside \texttt{[]} brackets. This display mode can be useful to correlate lines with the output of external tools, such as \texttt{llvm-mca}. To disable line numbering click the \RMB{}~right mouse button on a line number.

If the \emph{\faFileImport{}~Source locations} option is selected, each line of the assembly code will also contain information about the originating source file name and line number. Each file is assigned its own color for easier differentiation between different source files. Clicking the \LMB{}~left mouse button on a displayed source location will switch the source file, if necessary, and focus the source view on the selected line. Additionally, hovering the \faMousePointer{}~mouse cursor over the presented location will show a tooltip containing the name of a function the instruction originates from, along with an appropriate source code fragment and the local call stack if it exists.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bclampe
]{Local call stack}
In some cases, it may be challenging to understand what is being displayed in the disassembly. For example, calling the \texttt{std::lower\_bound} function may generate multiple levels of inlined functions: first, we enter the search algorithm, then the comparison functions, which in turn may be lambdas that call even more external code, and so on. In such an event, you will most likely see that some external code is taking a long time to execute, and you will be none the wiser on improving things.

The local call stack for an assembly instruction represents all the inline function calls \emph{within the symbol} (hence the 'local' part), which were made to reach the instruction. Deeper inspection of the local call stack, including navigation to the source call site of each participating inline function, can be performed through the context menu accessible by pressing the \RMB{}~right mouse button on the source location.
\end{bclogo}

Selecting the \emph{\faCogs{}~Raw code} option will enable the display of raw machine code bytes for each line. Individual bytes are displayed with interwoven colors to make reading easier.

If any instruction would jump to a predefined address, the symbolic name of the jump target will be additionally displayed. If the destination location is within the currently displayed symbol, an \texttt{->}~arrow will be prepended to the name. Hovering the \faMousePointer{}~mouse pointer over such symbol name will highlight the target location. Clicking on it with the \LMB{}~left mouse button will focus the view on the destination instruction or switch view to the destination symbol.

Enabling the \emph{\faShare{}~Jumps} option will show jumps within the symbol code as a series of arrows from the jump source to the jump target, and hovering the \faMousePointer{}~mouse pointer over a jump arrow will display a jump information tooltip. It will also draw the jump range on the scroll bar as a green line. A horizontal green line will mark the jump target location. Clicking on a jump arrow with the \LMB{}~left mouse button will focus the view on the target location. The \RMB{}~right mouse button opens a jump context menu, which allows inspection and navigation to the target location or any of the source locations. Jumps going out of the symbol\footnote{This includes jumps, procedure calls, and returns. For example, in x86 assembly the respective operand names can be: \texttt{jmp}, \texttt{call}, \texttt{ret}.} will be indicated by a smaller arrow pointing away from the code.

Portions of the executable used to show the symbol view are stored within the captured profile and don't rely on the available local disk files.

\subparagraph{Exploring microarchitecture}

If the listed assembly code targets x86 or x64 instruction set architectures, hovering \faMousePointer{}~mouse pointer over an instruction will display a tooltip with microarchitectural data, based on measurements made in \cite{Abel19a}. \emph{This information is retrieved from instruction cycle tables and does not represent the true behavior of the profiled code.} Reading the cited article will give you a detailed definition of the presented data, but here's a quick (and inaccurate) explanation:

\begin{itemize}
\item \emph{Throughput} -- How many cycles are required to execute an instruction in a stream of the same independent instructions. For example, if the CPU may execute two independent \texttt{add} instructions simultaneously on different execution units, then the throughput (cycle cost per instruction) is 0.5.
\item \emph{Latency} -- How many cycles it takes for an instruction to finish executing. This is reported as a min-max range, as some output values may be available earlier than the rest.
\item \emph{\textmu{}ops} -- How many microcode operations have to be dispatched for an instruction to retire. For example, adding a value from memory to a register may consist of two microinstructions: first load the value from memory, then add it to the register.
\item \emph{Ports} -- Which ports (execution units) are required for dispatch of microinstructions. For example, \texttt{2*p0+1*p015} would mean that out of the three microinstructions implementing the assembly instruction, two can only be executed on port 0, and one microinstruction can be executed on ports 0, 1, or 5. The number of available ports and their capabilities varies between different processors architectures. Refer to \url{https://wikichip.org/} for more information.
\end{itemize}

Selection of the CPU microarchitecture can be performed using the \emph{\faMicrochip{}~\textmu{}arch} drop-down. Each architecture is accompanied by the name of an example CPU implementing it. If the current selection matches the microarchitecture on which the profiled application was running, the \faMicrochip{}~icon will be green\footnote{Comparing sampled instruction counts with microarchitectural details only makes sense when this selection is properly matched.}. Otherwise, it will be red\footnote{You can use this to gain insight into how the code \emph{may} behave on other processors.}. Clicking on the \faMicrochip{}~icon when it is red will reset the selected microarchitecture to the one the profiled application was running on.

Clicking on the \emph{\faFileImport{}~Save} button lets you write the disassembly listing to a file. You can then manually extract some critical loop kernel and pass it to a CPU simulator, such as \emph{LLVM Machine Code Analyzer} (\texttt{llvm-mca})\footnote{\url{https://llvm.org/docs/CommandGuide/llvm-mca.html}}, to see how the code is executed and if there are any pipeline bubbles. Consult the \texttt{llvm-mca} documentation for more details. Alternatively, you might click the \RMB{}~right mouse button on a jump arrow and save only the instructions within the jump range, using the \emph{\faFileImport{}~Save jump range} button.

\subparagraph{Instruction dependencies}

Assembly instructions may read values stored in registers and may also write values to registers. As a result, a dependency between two instructions is created when one produces some result, which the other then consumes. Combining this dependency graph with information about instruction latencies may give a deep understanding of the bottlenecks in code performance.

Clicking the \LMB{}~left mouse button on any assembly instruction will mark it as a target for resolving register dependencies between instructions. To cancel this selection, click on any assembly instruction with \RMB{}~right mouse button.

The selected instruction will be highlighted in white, while its dependencies will be highlighted in red. Additionally, a list of dependent registers will be listed next to each instruction which reads or writes to them, with the following color code:

\begin{itemize}
\item \emph{Green} -- Register value is read (is a dependency \emph{after} target instruction).
\item \emph{Red} -- A value is written to a register (is a dependency \emph{before} target instruction).
\item \emph{Yellow} -- Register is read and then modified.
\item \emph{Grey} -- Value in a register is either discarded (overwritten) or was already consumed by an earlier instruction (i.e., it is readily available\footnote{This is actually a bit of simplification. Run a pipeline simulator, e.g., \texttt{llvm-mca} for a better analysis.}). The profiler will not follow the dependency chain further.
\end{itemize}

Search for dependencies follows program control flow, so there may be multiple producers and consumers for any single register. While the \emph{after} and \emph{before} guidelines mentioned above hold in the general case, things may be more complicated when there's a large number of conditional jumps in the code. Note that dependencies further away than 64 instructions are not displayed.

For more straightforward navigation, dependencies are also marked on the left side of the scroll bar, following the green, red and yellow conventions. The selected instruction is marked in blue.

\paragraph{Combined mode}

In this mode, the source and assembly panes will be displayed together, providing the best way to gain insight into the code. Hovering the \faMousePointer{}~mouse pointer over the source file line or the location of the assembly line will highlight the corresponding lines in the second pane (both in the listing and on the scroll bar). Clicking the \LMB{}~left mouse button on a line will select it and focus on it in both panes. Note that while an assembly line always has only one corresponding source line, a single source line may have many associated assembly lines, not necessarily next to each other. Clicking on the same \emph{source} line more than once will focus the \emph{assembly} view on the next associated instructions block.

\paragraph{Instruction pointer cost statistics}

If automated call stack sampling (see chapter~\ref{sampling}) was performed, additional profiling information will be available. The first column of source and assembly views will contain percentage counts of collected instruction pointer samples for each displayed line, both in numerical and graphical bar form. You can use this information to determine which function line takes the most time. The displayed percentage values are heat map color-coded, with the lowest values mapped to dark red and the highest to bright yellow. The color code will appear next to the percentage value and on the scroll bar so that you can identify 'hot' places in the code at a glance.

By default, samples are displayed only within the selected symbol, in isolation. In some cases, you may, however, want to include samples from functions that the selected symbol called. To do so, enable the \emph{\faSignOut*{}~Child calls} option, which you may also temporarily toggle by holding the \keys{Z} key. You can also click the~\faCaretDown{}~drop down control to display a child call distribution list, which shows each known function\footnote{You should remember that these are results of random sampling. Some function calls may be missing here.} that the symbol called. Make sure to familiarize yourself with section~\ref{readingcallstacks} to be able to read the results correctly.

Instruction timings can be viewed as a group. To begin constructing such a group, click the \LMB{}~left mouse button on the percentage value. Additional instructions can be added using the \keys{\ctrl}~key while holding the \keys{\shift}~key will allow selection of a range. To cancel the selection, click the \RMB{}~right mouse button on a percentage value. Group statistics can be seen at the bottom of the pane.

Clicking the \MMB{}~middle mouse button on the percentage value of an assembly instruction will display entry call stacks of the selected sample (see chapter~\ref{sampleparents}). This functionality is only available for instructions that have collected sampling data and only in the assembly view, as the source code may be inlined multiple times, which would result in ambiguous location data. Note that number of entry call stacks is displayed in a tooltip for a quick reference.

The sample data source is controlled by the \emph{\faSitemap{}~Function} control in the window header. If this option should be disabled, sample data will represent the whole symbol. If it is enabled, then the sample data will only include the selected function. You can change the currently selected function by opening the drop-down box, which includes time statistics. The time percentage values of each contributing function are calculated relative to the total number of samples collected within the symbol.

Selecting the \emph{Limit range} option will restrict counted samples to the time extent shared with the statistics view (displayed as a red-striped region on the timeline). See section~\ref{timeranges} for more detail.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcbombe
]{Important}
Be aware that the data is not entirely accurate, as it results from a random sampling of program execution. Furthermore, undocumented implementation details of an out-of-order CPU architecture will highly impact the measurement. Read chapter~\ref{checkenvironmentcpu} to see the tip of an iceberg.
\end{bclogo}

\paragraph{Inspecting hardware samples}

As described in chapter~\ref{hardwaresampling}, on some platforms, Tracy can capture the internal statistics counted by the CPU hardware. If this data has been collected, the \emph{\faHighlighter{}~Cost} selection list will be available. It allows changing what is taken into consideration for display by the cost statistics. You can select the following options:

\begin{itemize}
\item \emph{Sample count} -- this selects the instruction pointer statistics, collected by call stack sampling performed by the operating system. This is the default data shown when hardware samples have not been captured.
\item \emph{Cycles} -- an option very similar to the \emph{sample count}, but the data is collected directly by the CPU hardware counters. This may make the results more reliable.
\item \emph{Branch impact} -- indicates places where many branch instructions are issued, and at the same time, incorrectly predicted. Calculated as $\sqrt{\text{\#branch instructions}*\text{\#branch misses}}$. This is more useful than the raw branch miss rate, as it considers the number of events taking place.
\item \emph{Cache impact} -- similar to \emph{branch impact}, but it shows cache miss data instead. These values are calculated as $\sqrt{\text{\#cache references}*\text{\#cache misses}}$ and will highlight places with lots of cache accesses that also miss.
\item The rest of the available selections just show raw values gathered from the hardware counters. These are: \emph{Retirements}, \emph{Branches taken}, \emph{Branch miss}, \emph{Cache access} and \emph{Cache miss}.
\end{itemize}

If the \emph{\faHammer{}~HW} (hardware samples) switch is enabled, the profiler will supplement the cost percentages column with three additional columns. The first added column displays the instructions per cycle (IPC) value. The two remaining columns show branch and cache data, as described below. The displayed values are color-coded, with green indicating good execution performance and red indicating that the code stalled the CPU pipeline for one reason or another.

If the \emph{\faCarCrash{}~Impact} switch is enabled, the branch and cache columns will show how much impact the branch mispredictions and cache misses have. The way these statistics are calculated is described in the list above. In the other case, the columns will show the raw branch and cache miss rate ratios, isolated to their respective source and assembly lines and not relative to the whole symbol.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcattention
]{Isolated values}
The percentage values when \emph{\faCarCrash{}~Impact} option is not selected will not take into account the relative count of events. For example, you may see a 100\% cache miss rate when some instruction missed 10 out of 10 cache accesses. While not ideal, this is not as important as a seemingly better 50\% cache miss rate instruction, which actually has missed 1000 out of 2000 accesses. Therefore, you should always cross-check the presented information with the respective event counts. To help with this, Tracy will dim statistically unimportant values.
\end{bclogo}

\subsection{Wait stacks window}
\label{waitstackswindow}

If wait stack information has been captured (chapter~\ref{waitstacks}), here you will be able to inspect the collected data. There are three different views available:

\begin{itemize}
\item \emph{\faTable{}~List} -- shows all unique wait stacks, sorted by the number of times they were observed.
\item \emph{\faTree{}~Bottom-up tree} -- displays wait stacks in the form of a collapsible tree, which starts at the bottom of the call stack.
\item \emph{\faTree{}~Top-down tree} -- displays wait stacks in the form of a collapsible tree, which starts at the top of the call stack.
\end{itemize}

Displayed data may be narrowed down to a specific time range or to include only selected threads.

\subsection{Lock information window}
\label{lockwindow}

This window presents information and statistics about a lock. The lock events count represents the total number collected of wait, obtain and release events. The announce, termination, and lock lifetime measure the time from the lockable construction until destruction.

\subsection{Frame image playback window}
\label{playback}

You may view a live replay of the profiled application screen captures (see section~\ref{frameimages}) using this window. Playback is controlled by the \emph{\faPlay~Play} and \emph{\faPause~Pause} buttons and the \emph{Frame image} slider can be used to scrub to the desired timestamp. Alternatively you may use the \emph{\faCaretLeft} and \emph{\faCaretRight} buttons to change single frame back or forward.

If the \emph{Sync timeline} option is selected, the profiler will focus the timeline view on the frame corresponding to the currently displayed screenshot. The \emph{Zoom 2$\times$} option enlarges the image for easier viewing.

The following parameters also accompany each displayed frame image: \emph{timestamp}, showing at which time the image was captured, \emph{frame}, displaying the numerical value of the corresponding frame, and \emph{ratio}, telling how well the in-memory loss-less compression was able to reduce the image data size.

\subsection{CPU data window}
\label{cpudata}

Statistical data about all processes running on the system during the capture is available in this window if the profiler performed context switch capture (section~\ref{contextswitches}).

Each running program has an assigned process identifier (PID), which is displayed in the first column. The profiler will also display a list of thread identifiers (TIDs) if a program entry is expanded.

The \emph{running time} column shows how much processor time was used by a process or thread. The percentage may be over 100\%, as it is scaled to trace length, and multiple threads belonging to a single program may be executing simultaneously. The \emph{running regions} column displays how many times a given entry was in the \emph{running} state, and the \emph{CPU migrations} shows how many times an entry was moved from one CPU core to another when the system scheduler suspended an entry.

The profiled program is highlighted using green color. Furthermore, the yellow highlight indicates threads known to the profiler (that is, which sent events due to instrumentation).

\subsection{Annotation settings window}
\label{annotationsettings}

In this window, you may modify how a timeline annotation (section~\ref{annotatingtrace}) is presented by setting its text description or selecting region highlight color. If the note is no longer needed, you may also remove it here.

\subsection{Annotation list window}
\label{annotationlist}

This window lists all annotations marked on the timeline. Each annotation is presented, as shown on figure~\ref{figannlist}. From left to right the elements are:

\begin{itemize}
\item \emph{\faEdit{} Edit} -- Opens the annotation settings window (section~\ref{annotationsettings}).
\item \emph{\faMicroscope{} Zoom} -- Zooms timeline to the annotation extent.
\item \emph{\faTrash*{} Remove} -- Removes the annotation. You must press the \keys{\ctrl} key to enable this button.
\item Colored box -- Color of the annotation.
\item Text description of the annotation.
\end{itemize}

\begin{figure}[h]
\centering\begin{tikzpicture}
\draw[rounded corners=5pt] (0.0, 0) rectangle+(0.5, -0.5) node [midway] {\faEdit};
\draw[rounded corners=5pt] (0.6, 0) rectangle+(0.5, -0.5) node [midway] {\faMicroscope};
\draw[rounded corners=5pt] (1.2, 0) rectangle+(0.5, -0.5) node [midway] {\faTrash*};
\draw[rounded corners=5pt, pattern=crosshatch dots] (1.8, 0) rectangle+(0.5, -0.5);
\draw[rounded corners=5pt] (2.4, 0) node[anchor=north west] {Text description};
\end{tikzpicture}
\caption{Annotation list entry}
\label{figannlist}
\end{figure}

A new view-sized annotation can be added in this window by pressing the \emph{\faPlus{}~Add annotation} button. This effectively saves your current viewport for further reference.

\subsection{Time range limits}
\label{timerangelimits}

This window displays information about time range limits (section~\ref{timeranges}) for find zone (section~\ref{findzone}), statistics (section~\ref{statistics}), memory (section~\ref{memorywindow}) and wait stacks (section~\ref{waitstackswindow}) results. Each limit can be enabled or disabled and adjusted through the following options:

\begin{itemize}
\item \emph{Limit to view} -- Set the time range limit to current view.
\item \emph{\faMicroscope{}~Focus} -- Set the timeline view to the time range extent.
\item \emph{\faStickyNote{}~Set from annotation} -- Allows using the annotation region for limiting purposes.
\item \emph{\faSortAmountUp{}~Copy from statistics} -- Copies the statistics time range limit.
\item \emph{\faSearch{}~Copy from find zone} -- Copies the find zone time range limit.
\item \emph{\faHourglassHalf{}~Copy from wait stacks} -- Copies the wait stacks time range limit.
\item \emph{\faMemory{}~Copy from memory} -- Copies the memory time range limit.
\end{itemize}

Note that ranges displayed in the window have color hints that match the color of the striped regions on the timeline.

\section{Exporting zone statistics to CSV}
\label{csvexport}

You can use a command-line utility in the \texttt{csvexport} directory to export primary zone statistics from a saved trace into a CSV format.
The tool requires a single .tracy file as an argument and prints the result into the standard output (stdout), from where you can redirect it into a file or use it as an input into another tool.
By default, the utility will list all zones with the following columns:

\begin{itemize}
  \item \texttt{name} -- Zone name
  \item \texttt{src\_file} -- Source file where the zone was set
  \item \texttt{src\_line} -- Line in the source file where the zone was set
  \item \texttt{total\_ns} -- Total zone time in nanoseconds
  \item \texttt{total\_perc} -- Total zone time as a percentage of the program's execution time
  \item \texttt{counts} -- Zone count
  \item \texttt{mean\_ns} -- Mean zone time (equivalent to MPTC in the profiler GUI) in nanoseconds
  \item \texttt{min\_ns} -- Minimum zone time in nanoseconds
  \item \texttt{max\_ns} -- Maximum zone time in nanoseconds
  \item \texttt{std\_ns} -- Standard deviation of the zone time in nanoseconds
\end{itemize}

You can customize the output with the following command line options:

\begin{itemize}
  \item \texttt{-h, -\hspace{-1.25ex} -help} -- Display a help message
  \item \texttt{-f, -\hspace{-1.25ex} -filter <name>} -- Filter the zone names
  \item \texttt{-c, -\hspace{-1.25ex} -case} -- Make the name filtering case sensitive
  \item \texttt{-s, -\hspace{-1.25ex} -sep <separator>} -- Customize the CSV separator (default is ``\texttt{,}'')
  \item \texttt{-e, -\hspace{-1.25ex} -self} -- Use self time (equivalent to the ``Self time'' toggle in the profiler GUI)
  \item \texttt{-u, -\hspace{-1.25ex} -unwrap} -- Report each zone individually; this will discard the statistics columns and instead report the timestamp and duration for each zone entry
\end{itemize}

\section{Importing external profiling data}
\label{importingdata}

Tracy can import data generated by other profilers. This external data cannot be directly loaded but must be converted first. Currently, there's only support for converting chrome:tracing data through the \texttt{import-chrome} utility.

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bclampe
]{Compressed traces}
Tracy can import traces compressed with the Zstandard algorithm (for example, using the \texttt{zstd} command-line utility). Traces ending with \texttt{.zst} extension are assumed to be compressed.
\end{bclogo}

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bclampe
]{Source locations}
Chrome tracing format doesn't document a way to provide source location data. The \texttt{import-chrome} utility will however recognize a custom \texttt{loc} tag in the root of zone begin events. You should be formatting this data in the usual \texttt{filename:line} style, for example: \texttt{hello.c:42}. Providing the line number (including a colon) is optional but highly recommended.
\end{bclogo}

\begin{bclogo}[
noborder=true,
couleur=black!5,
logo=\bcattention
]{Limitations}
\begin{itemize}
\item Tracy is a single-process profiler. Should the imported trace contain PID entries, each PID+TID pair will create a new \emph{pseudo-TID} number, which the profiler will then decode into a PID+TID pair in thread labels. If you want to preserve the original TID numbers, your traces should omit PID entries.
\item The imported data may be severely limited, either by not mapping directly to the data structures used by Tracy or by following undocumented practices.
\end{itemize}
\end{bclogo}

\section{Configuration files}
\label{configurationfiles}

While the client part doesn't read or write anything to the disk (except for accessing the \texttt{/proc} filesystem on Linux), the server part has to keep some persistent state. The naming conventions or internal data format of the files are not meant to be known by profiler users, but you may want to do a backup of the configuration or move it to another machine.

On Windows settings are stored in the \texttt{\%APPDATA\%/tracy} directory. All other platforms use the \texttt{\$XDG\_CONFIG\_HOME/tracy} directory, or \texttt{\$HOME/.config/tracy} if the \texttt{XDG\_CONFIG\_HOME} environment variable is not set.

\subsection{Root directory}

Various files at the root configuration directory store common profiler state such as UI windows position, connections history, etc.

\subsection{Trace specific settings}
\label{tracespecific}

Trace files saved on disk are immutable and can't be changed. Still, it may be desirable to store additional per-trace information to be used by the profiler, for example, a custom description of the trace or the timeline view position used in the previous profiling session.

This external data is stored in the \texttt{user/[letter]/[program]/[week]/[epoch]} directory, relative to the configuration's root directory. The \texttt{program} part is the name of the profiled application (for example \texttt{program.exe}). The \texttt{letter} part is the first letter of the profiled application's name. The \texttt{week} part is a count of weeks since the Unix epoch, and the \texttt{epoch} part is a count of seconds since the Unix epoch. This rather unusual convention prevents the creation of directories with hundreds of entries.

The profiler never prunes user settings.

\newpage
\appendix
\appendixpage

\section{License}

\verbatiminput{../LICENSE.}

\section{List of contributors}

\verbatiminput{../AUTHORS.}

\section{Inventory of external libraries}

The following libraries are included with and used by the Tracy Profiler. Entries marked with a \faStar{}~icon are used in the client code.

\begin{itemize}
\item 3-clause BSD license
\begin{itemize}
\item getopt\_port -- \url{https://github.com/kimgr/getopt\_port}
\item libbacktrace \faStar{} -- \url{https://github.com/ianlancetaylor/libbacktrace}
\item Zstandard -- \url{https://github.com/facebook/zstd}
\item Diff Template Library -- \url{https://github.com/cubicdaiya/dtl}
\end{itemize}

\item 2-clause BSD license
\begin{itemize}
\item concurrentqueue \faStar{} -- \url{https://github.com/cameron314/concurrentqueue}
\item LZ4 \faStar{} -- \url{https://github.com/lz4/lz4}
\item xxHash -- \url{https://github.com/Cyan4973/xxHash}
\end{itemize}

\item Public domain
\begin{itemize}
\item rpmalloc \faStar{} -- \url{https://github.com/rampantpixels/rpmalloc}
\item gl3w -- \url{https://github.com/skaslev/gl3w}
\item stb\_image -- \url{https://github.com/nothings/stb}
\item stb\_image\_resize -- \url{https://github.com/nothings/stb}
\end{itemize}

\item zlib license
\begin{itemize}
\item Native File Dialog Extended -- \url{https://github.com/btzy/nativefiledialog-extended}
\item IconFontCppHeaders -- \url{https://github.com/juliettef/IconFontCppHeaders}
\item pdqsort -- \url{https://github.com/orlp/pdqsort}
\end{itemize}

\item MIT license
\begin{itemize}
\item Dear ImGui -- \url{https://github.com/ocornut/imgui}
\item JSON for Modern C++ -- \url{https://github.com/nlohmann/json}
\item robin-hood-hashing -- \url{https://github.com/martinus/robin-hood-hashing}
\item SPSCQueue \faStar{} -- \url{https://github.com/rigtorp/SPSCQueue}
\end{itemize}

\item Apache license 2.0
\begin{itemize}
\item Droid Sans -- \url{https://www.fontsquirrel.com/fonts/droid-sans}
\end{itemize}

\item SIL Open Font License 1.1
\begin{itemize}
\item Fira Code -- \url{https://github.com/tonsky/FiraCode}
\item Font Awesome -- \url{https://fontawesome.com/}
\end{itemize}

\end{itemize}

\bibliographystyle{alpha}
\bibliography{tracy}

\end{document}
