This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,5 @@
* [Unity Profiling Core Package](index.md)
* [What's new](whats-new.md)
* [Upgrade guide](upgrade-guide.md)
* [ProfilerMarker API guide](profilermarker-guide.md)
* [Profiler Counter API guide](profilercounter-guide.md)
@@ -0,0 +1,24 @@
apiRules:
- exclude:
# inherited Object methods
uidRegex: ^System\.Object\..*$
type: Method
- exclude:
# mentioning types from System.* namespace
uidRegex: ^System\..*$
type: Type
- exclude:
hasAttribute:
uid: System.ObsoleteAttribute
type: Member
- exclude:
hasAttribute:
uid: System.ObsoleteAttribute
type: Type
- exclude:
uidRegex: Tests$
type: Namespace
- exclude:
# ProfilerMarker.Auto helper struct
uidRegex: ^Unity.Profiling.ProfilerMarker.*AutoScope$
type: Type
@@ -0,0 +1,18 @@
# About Unity Profiling Core
Use the Unity Profiling Core package to add contextual information to the [Unity Profiler](https://docs.unity3d.com/Manual/Profiler.html) captures. You can use the [Scripting APIs](https://docs.unity3d.com/Packages/com.unity.profiling.core@latest?subfolder=/api/index.html) provided with the Unity Profiling Core package to add a string or number to a Profiler sample or pass custom data to the Profiler data stream to later use in the Editor.
## Installation
To install this package, follow the instructions in the [Package Manager documentation](https://docs.unity3d.com/Manual/upm-ui-install.html). The Unity Profiling Core package is not discoverable in the Package Manager UI because it is a core package. Therefore the recommended installation method is to [add the package by name](https://docs.unity3d.com/2021.2/Documentation/Manual/upm-ui-quick.html), which is `com.unity.profiling.core`. If you are using Unity 2021.2.0a5 or newer, you can also install it via [this link](com.unity3d.kharma:upmpackage/com.unity.profiling.core).
![Install Package By Name](images/install_package_by_name.png)<br/>*Install package by name.*
## Requirements
This version of Unity Profiling Core is compatible with the following versions of the Unity Editor:
* 2020.1 and later
## Helpful links
If you are new to Unity Profiling Core, or have a question after reading the documentation, you can:
* Watch the [Tutorials](https://learn.unity.com/tutorial/introduction-to-the-profiler) here.
* Join our [support forum](https://forum.unity.com/forums/profiler-previews.199/).
@@ -0,0 +1,189 @@
# Profiler counters API guide
You can use the `ProfilerCounter` or `ProfilerCounterValue` API to track the integral metrics of your application and make them visible in the Unity Profiler or in other code. This is particularly useful if you want to track performance changes in your application, and it speeds up the investigation of performance issues because you can use the information from your Profiler counters in conjunction with Unity built-in counters and instrumentation data.
If you are an Asset Store package developer, you can add Profiler counters to your code to help other developers to understand important performance characteristics of your system, and they can use this information for optimization or budgeting tooling.
The following diagram displays a high level overview of the Profiler counters data flow:
![Profiler counters flow.](images/profilercounter_flow.png)<br/>*Profiler counters flow.*
The [ProfilerRecorder](https://docs.unity3d.com/ScriptReference/Unity.Profiling.ProfilerRecorder.html) API retrieves Profiler counter data in your application code, and the [RawFrameDataView](https://docs.unity3d.com/ScriptReference/Profiling.RawFrameDataView.html) or [HierarchyFrameDataView](https://docs.unity3d.com/ScriptReference/Profiling.HierarchyFrameDataView.html) APIs retrieves Profiler counter data in the Editor code. Additionally, you can visualize this counter data in the Profiler Window by [configuring a custom Profiler Module in the Module Editor](#viewing-counters).
`ProfilerCounter` and `ProfilerCounterValue` support the following types:
* int
* long
* float
* double
## How to pass counter values to the Profiler
The Profiler counters API supports push and pull operations. You can push the value of the counter to the Profiler, or the Profiler can pull the value at the end of the frame.
If your data changes infrequently - for example once per frame, use the `ProfilerCounter` API to push the counter data to the Profiler. If your data changes multiple times per frame, use the `ProfilerCounterValue` API. This makes the Profiler automatically pick up the last value at the end of the frame. The following example shows you how to use these APIs to set up and pass counter values to the Profiler
### 1. Define counters
To pass counter values to the Profiler, you must first define which counters you want to send. The following example uses `ProfilerCounter` for the enemies count because the value changes infrequently. Additionally, the example uses `ProfilerCounterValue` for bullet count because a player or enemies might fire many bullets per frame.
```C#
using Unity.Profiling;
class GameStats
{
public static readonly ProfilerCategory MyProfilerCategory = ProfilerCategory.Scripts;
public static readonly ProfilerCounter<int> EnemyCount =
new ProfilerCounter<int>(MyProfilerCategory, "Enemy Count", ProfilerMarkerDataUnit.Count);
public static ProfilerCounterValue<int> BulletCount =
new ProfilerCounterValue<int>(MyProfilerCategory, "Bullet Count",
ProfilerMarkerDataUnit.Count, ProfilerCounterOptions.FlushOnEndOfFrame);
}
```
### 2. Update the value
The next example assumes that the `GameManager` class handles high level logic and knows about enemies. To update the value of the counter, in the `Update` or `LateUpdate` method (depending on when the logic is performed with spawning or destroying enemies), you can use `Sample` method to push the enemies count value to the Profiler.
```c#
using UnityEngine;
using Unity.Profiling;
class GameManager : MonoBehaviour
{
Enemy[] m_Enemies;
void Update()
{
GameStats.EnemyCount.Sample(m_Enemies.Length);
}
}
```
To pass the bullet count to the Profiler, this example assumes that there is a Shell script that manages the bullet lifecycle. It then increases the `GameStats.BulletCount` value in `Awake` and decreases it in `OnDestroy` to give accurate information about the current bullet flow in the game.
```c#
using UnityEngine;
using Unity.Profiling;
public class Shell : MonoBehaviour
{
void Awake()
{
GameStats.BulletCount.Value += 1;
}
void OnDestroy()
{
GameStats.BulletCount.Value -= 1;
}
}
```
>[!NOTE]
>Both `ProfilerCounter` and `ProfilerCounterValue` are compiled out in non-development builds.
<a name="viewing-counters"> </a>
## Viewing the counters in the Profiler Window
You can view the data that `ProfilerCounter` or `ProfilerCounterValue` generates in the Profiler Window in a custom Profiler Module. This might help to visually recognise relationships with other system metrics and identify performance issues quickly. You can use the Module Editor to select built-in or newly added counters for the visualization. To open the Profiler Module Editor, open the Profiler Window (**Window &gt; Analysis &gt; Profiler**) and then select the Profiler Module dropdown in the top left of the window. Click the gear icon, and the Profiler Module Editor opens in a new window.
![Profiler Module Editor](images/profilermoduleeditor.png)<br/>*Profiler Module Editor window.*
You can then view the data in the Profiler Window alongside with other counters.
![Module with custom counters in Profiler Window.](images/mystatsmodule.png)<br/>*Module with custom counters in the Profiler Window.*
>[!NOTE]
>Counters declared as `static` are dynamically initialized in the C# code when a type is initialized and might not be available until they are actually initialized and used. This applies to both Edit and Play Modes.
If you don't see your counters appearing in the Module Editor, record some data with the profiler first until some frames passed that should have send values through these counters.
## Getting counter values in Players
Profiler counters give you an insight into important game or engine system metrics. If you have a continuous integration setup or want to visualize key performance metrics in your application during a test play through you can use the [ProfilerRecorder](https://docs.unity3d.com/ScriptReference/Unity.Profiling.ProfilerRecorder.html) API to get custom Profiler counter values as well as Unity built-in counters.
For example, the following script displays the frame time, Mono/IL2CPP heap size, and total memory that the application uses.
```c#
using System.Collections.Generic;
using System.Text;
using Unity.Profiling;
using UnityEngine;
public class StatsScript : MonoBehaviour
{
string statsText;
ProfilerRecorder systemMemoryRecorder;
ProfilerRecorder gcMemoryRecorder;
ProfilerRecorder mainThreadTimeRecorder;
double GetRecorderFrameAverage(ProfilerRecorder recorder)
{
var samplesCount = recorder.Capacity;
if (samplesCount == 0)
return 0;
double r = 0;
unsafe
{
var samples = stackalloc ProfilerRecorderSample[samplesCount];
recorder.CopyTo(samples, samplesCount);
for (var i = 0; i < samplesCount; ++i)
r += samples[i].Value;
r /= samplesCount;
}
return r;
}
void OnEnable()
{
systemMemoryRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Memory, "System Used Memory");
gcMemoryRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Memory, "GC Reserved Memory");
mainThreadTimeRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Internal, "Main Thread", 15);
}
void OnDisable()
{
systemMemoryRecorder.Dispose();
gcMemoryRecorder.Dispose();
mainThreadTimeRecorder.Dispose();
}
void Update()
{
var sb = new StringBuilder(500);
sb.AppendLine($"Frame Time: {GetRecorderFrameAverage(mainThreadTimeRecorder) * (1e-6f):F1} ms");
sb.AppendLine($"GC Memory: {gcMemoryRecorder.LastValue / (1024 * 1024)} MB");
sb.AppendLine($"System Memory: {systemMemoryRecorder.LastValue / (1024 * 1024)} MB");
statsText = sb.ToString();
}
void OnGUI()
{
GUI.TextArea(new Rect(10, 30, 250, 50), statsText);
}
}
```
Don't forget to use `ProfilerRecorder.Dispose()` to free unmanaged resources associated with the `ProfilerRecorder`.
>[!NOTE]
>Not all Profiler counters are available in the Release Players. Use [ProfilerRecorder.Valid](https://docs.unity3d.com/ScriptReference/Unity.Profiling.ProfilerRecorder.Valid.html) to determine if the data is available and that the Profiler can record it. Alternatively, you can use [ProfilerRecorderHandle.GetAvailable](https://docs.unity3d.com/ScriptReference/Unity.Profiling.LowLevel.Unsafe.ProfilerRecorderHandle.GetAvailable.html) to enumerate all available Profiler stats.
## Getting counter values from Profiler Frame data in the Editor
To get Profiler counter values when processing Profiler frame data in the Editor, use the [FrameDataView](https://docs.unity3d.com/ScriptReference/Profiling.FrameDataView.html) API.
You can use the [FrameDataView.GetCounterValueAsInt](https://docs.unity3d.com/ScriptReference/Profiling.FrameDataView.GetCounterValueAsInt.html), [FrameDataView.GetCounterValueAsLong](https://docs.unity3d.com/ScriptReference/Profiling.FrameDataView.GetCounterValueAsLong.html), [FrameDataView.GetCounterValueAsFloat](https://docs.unity3d.com/ScriptReference/Profiling.FrameDataView.GetCounterValueAsFloat.html) and [FrameDataView.GetCounterValueAsDouble](https://docs.unity3d.com/ScriptReference/Profiling.FrameDataView.GetCounterValueAsDouble.html) to get a frame value of the specific counter, like so:
```c#
using UnityEditor.Profiling;
class Example
{
static int ExtractMyCounterValue(FrameDataView frameData, string counterName)
{
var counterMarkerId = frameData.GetMarkerId(counterName);
return frameData.GetCounterValueAsInt(counterMarkerId);
}
}
```
@@ -0,0 +1,117 @@
# ProfilerMarker API guide
Use ProfilerMarker to mark up resource-intensive script code blocks and make them visible in the Unity Profiler.
This can be useful because by default, the built-in Unity Profiler does not profile all method calls. Also, if you enable **Deep Profiling**, it causes a large overhead that significantly slows down your application execution and skews the results.
To use the [ProfilerMarker API](https://docs.unity3d.com/ScriptReference/Unity.Profiling.ProfilerMarker.html), start your code with `ProfilerMarker.Begin()` and end it with `ProfilerMarker.End()` like the following:
```C#
using UnityEngine;
using Unity.Profiling;
public class ProfilerMarkerExample
{
static readonly ProfilerMarker k_MyCodeMarker = new ProfilerMarker("My Code");
void Update() {
k_MyCodeMarker.Begin();
Debug.Log("This code is being profiled");
k_MyCodeMarker.End();
}
}
```
Unity then records and reports that code block's execution time to the Profiler, and displays it in the [CPU Profiler module](https://docs.unity3d.com/Manual/ProfilerCPU.html) without the need to use Deep Profiling. It displays it as a new entry in the **Hierarchy View** of the CPU Profiler module, as follows:
![Profiler sample in Profiler Window.](images/profilerwindow.png)<br/>*Profiler sample in Profiler Window.*
You can also capture this information with the [Recorder profiling API](https://docs.unity3d.com/ScriptReference/Profiling.Recorder.html). During development in the Editor and in Development Players, you can use it to get a performance overview of the different parts of your code and to identify performance issues.
You can add as many Profiler samples as you like: these calls have zero overhead when Unity deploys them in a non-development build. `Begin` and `End` methods are marked with ConditionalAttribute. Unity conditionally compiles them away, and as such, they have zero execution overhead in non-developmenet (Release) builds. The marker field will be present in release build though, taking up memory for it's IntPtr, i.e. 8 Byte.
`ProfilerMarker` represents a named Profiler handle and is the most efficient way of profiling your code. You can use it in any C# code of your application.
## How to add instrumentation to C# code
You can also use `ProfilerMarker.Auto()` in your code to ensure that `ProfilerMarker.End()` is automatically called at the end of the code block. The following calls are equivalent:
```C#
using Unity.Profiling;
public class MySystemClass
{
static readonly ProfilerMarker k_UpdatePerfMarker = new ProfilerMarker("MySystem.Update");
public void Update()
{
k_UpdatePerfMarker.Begin();
// ...
k_UpdatePerfMarker.End();
using (k_UpdatePerfMarker.Auto())
{
// ...
}
}
}
```
`ProfilerMarker.Auto()` can not be compiled out in non-development (Release) builds but just returns null and thus adding minimal overhead.
## How to add integer or floating point parameters to instrumentation sample
Sometimes you might want to provide additional context to your code samples, to identify specific conditions on why the code might have been running for a long time. For example, if your system is carrying out simulations of a number of objects, you can pass the number of objects with a Profiler sample. If you then see an abnormal number along with a long sample duration, that might mean you have to use another thread for simulation or split the CPU work across multiple frames (timeslicing) or even do a game design adjustments to prevent frame drops.
```C#
using Unity.Profiling;
public class MySystemClass
{
static readonly ProfilerMarker<int> k_PreparePerfMarker = new ProfilerMarker<int>("MySystem.Prepare", "Objects Count");
static readonly ProfilerMarker<float> k_SimulatePerfMarker = new ProfilerMarker<float>(ProfilerCategory.Scripts, "MySystem.Simulate", "Objects Density");
public void Update(int objectsCount)
{
k_PreparePerfMarker.Begin(objectsCount);
// ...
k_PreparePerfMarker.End();
using (k_SimulatePerfMarker.Auto(objectsCount * 1.0f))
{
// ...
}
}
}
```
**Note:** The ProfilerMarker supports up to three numeric parameters: [ProfilerMarker\<TP1\>](../api/Unity.Profiling.ProfilerMarker-1.html), [ProfilerMarker\<TP1, TP2\>](../api/Unity.Profiling.ProfilerMarker-2.html) and [ProfilerMarker\<TP1, TP2, TP3\>](../api/Unity.Profiling.ProfilerMarker-3.html).
## How to add string parameter to instrumentation sample
Similarly, when you load level or data files you might want to see the name of the level or file which took longer than expected to process. Use [ProfilerMarkerExtension](../api/Unity.Profiling.ProfilerMarkerExtension.html) methods to pass a string parameter along with a Profiler sample:
```C#
using Unity.Profiling;
public class MySystemClass
{
static readonly ProfilerMarker k_PreparePerfMarker = new ProfilerMarker("MySystem.Prepare");
public void Prepare(string path)
{
k_PreparePerfMarker.Begin(path);
// ...
k_PreparePerfMarker.End();
}
}
```
## Where to see the sample parameters in Profiler Window
The samples that `ProfilerMarker.Begin()/End()` or `ProfilerMarker.Auto` generates are visible in **Timeline View** and **Hierarchy View** of the CPU module in the Profiler Window.
![Profiler sample with metadata in Timeline View.](images/timelineview_metadata.png)<br/>*Profiler sample with metadata in Timeline View.*
![Profiler sample with metadata in Hierarchy View.](images/hierarchyview_metadata.png)<br/>*Profiler sample with metadata in Hierarchy View.*
@@ -0,0 +1,3 @@
# Profiling Core upgrade guide
You do not need to take any actions to upgrade your project to this package version.
@@ -0,0 +1,3 @@
# Profiling Core what's new guide
This is a new package release. In future package versions, this page will display a summary of updates and changes for that version.