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,13 @@
* [Performance Testing Package overview](./index.md)
* [Taking measurements](./taking-measurements.md)
* [Measure.Method](./measure-method.md)
* [Measure.Frames](./measure-frames.md)
* [Measure.Scope](./measure-scope.md)
* [Measure.ProfileMarkers](./measure-profile-markers.md)
* [Measure.Custom](./measure-custom.md)
* [Writing tests](./writing-tests.md)
* [Viewing results](./viewing-results.md)
* [Reference]
* [Classes](./classes.md)
* [Test attributes](./test-attributes.md)
* [Command-line arguments](./cmd-line-args.md)
@@ -0,0 +1,16 @@
# Classes
This section contains a reference for classes relevant when working with the Performance Testing Package.
## SampleGroup
**class SampleGroup** - represents a group of samples with the same purpose that share a name, sample unit and whether
an increase is better.
Optional parameters
- **Name** : Name of the measurement. If unspecified, "Time" is used as the default name.
- **Unit** : Unit of the measurement to report samples in. Possible values are:
Nanosecond, Microsecond, Millisecond, Second, Byte, Kilobyte, Megabyte, Gigabyte
- **IncreaseIsBetter** : If true, an increase in the measurement value is considered a performance improvement (
progression). If false, an increase is treated as a performance regression. False by default.
@@ -0,0 +1,29 @@
# Command-line arguments
This section lists Unity arguments supported by the package when running performance tests from the command line. For a
general overview of the topic, see
the [Unity Test Framework documentation](https://docs.unity3d.com/Packages/com.unity.test-framework@latest).
## Supported arguments
### perfTestResults
The path where Unity should save the JSON file with performance test run results. By default, Unity saves it in
the [Application.persistentDataPath](https://docs.unity3d.com/ScriptReference/Application-persistentDataPath.html)
folder, and, if you specify the `testResults` argument of the Unity Test Framework package, in the folder that holds the
NUnit test results file as well.
Please note that when this argument is not provided, Unity generates two report files at the default results location -
the JSON file with performance test run results as well as the NUnit test results XML file that these results are
extracted from. This behaviour currently exists for backwards compatibility reasons and will be deprecated over time, as
the destination path of the test results XML file is already controlled by the `testResults` command-line argument of
the Unity Test Framework package.
Unity updates the results file after each test finishes rather than only when the run completes, so a run that ends
unexpectedly still leaves the results that it had already measured on disk.
## Example of command-line usage
```bash
Unity.exe -runTests -batchmode -projectPath PATH_TO_YOUR_PROJECT -testResults C:\temp\results.xml -perfTestResults C:\temp\perfResults.json
```
@@ -0,0 +1,122 @@
# Performance Testing Package for Unity Test Framework
The Unity Performance Testing Package extends Unity Test Framework with performance testing capabilities. It provides an
API and test case decorators for taking measurements/samples of Unity profiler markers, and other custom metrics, in the
Unity Editor and built players. It also collects configuration metadata that is useful for comparing data across
different hardware and configurations, such as build and player settings.
The Performance Testing Package is intended for use with the Unity Test Framework. You should be familiar with how to
create and run tests as described in
the [Unity Test Framework documentation](https://docs.unity3d.com/Packages/com.unity.test-framework@latest).
> **Note:** When tests are run with Unity Test Framework, a development player is always built to support communication
> between the editor and player, effectively overriding the development build setting from the build settings UI or
> scripting API.
## Installing the Performance Testing Package
From Unity version 6000.6 the Performance Testing package is a [Core package](https://docs.unity3d.com/Manual/pack-core.html) which is automatically installed with the Unity Editor.
To install this package with an older supported Unity version, use the [Package Manager](https://docs.unity3d.com/Manual/upm-ui-actions.html).
When the package is installed, add a reference to `Unity.PerformanceTesting` in your assembly definition to access the
performance testing APIs.
![Performance test example01](images/example04.png)
## Unity version compatibility
Unity releases can often include changes that break compatibility with the Performance Testing Package, so we cannot
currently guarantee latest package version compatability with every Unity version. The table below shows which version
of the package is compatible with which Unity release streams.
| Unity stream | Package version |
|--------------|-----------------|
| 6000.7 | 6.7.0 |
| 6000.6 | 6.6.0 |
| 6000.3 | 3.5.0 |
| 6000.0 | 3.5.0 |
| 2022.3 | 3.5.0 |
| 2020.3 | 3.5.0 |
## Tips
### Project settings
- Remove all but one of the [Quality level settings](https://docs.unity3d.com/Manual/class-QualitySettings.html) in *
*Project Settings > Quality**. Otherwise, you may have different configurations when running on different platforms.
If you require different settings per platform then make sure they are being set as expected.
- Disable VSync under **Project Settings > Quality**. Some platforms like Android have a forced VSync and this will not
be possible.
- Disable HW Reporting **PlayerSettings -> Other -> Disable HW Reporting**.
- Remove camera and run in batchmode if you are not measuring rendering.
### Generating assets
Use [IPrebuildSetup](https://docs.unity3d.com/Packages/com.unity.test-framework@1.1/api/UnityEngine.TestTools.IPrebuildSetup.html)
attribute when you need to generate assets.
Place assets in Resources or [StreamingAssets](https://docs.unity3d.com/Manual/SpecialFolders.html) folders, scenes can
be placed anywhere in the project, but should be added to build settings.
#### Example 1: IPrebuildSetup implementation
``` csharp
public class TestsWithPrebuildStep : IPrebuildSetup
{
public void Setup()
{
// this code is executed before entering playmode or the player is executed
}
}
public class MyAmazingPerformanceTest
{
[Test, Performance]
[PrebuildSetup(typeof(TestsWithPrebuildStep))]
public void Test()
{
...
}
}
```
When loading scenes in IPrebuildSetup you have to use `LoadSceneMode.Additive`.
#### Example 2: Using EditorSceneManager to create new scenes additively, save and add them to build settings.
``` csharp
private static string m_ArtifactsPath = "Assets/Artifacts/";
public static Scene NewScene(NewSceneSetup setup)
{
Scene scene = EditorSceneManager.NewScene(setup, NewSceneMode.Additive);
EditorSceneManager.SetActiveScene(scene);
return scene;
}
public static void SaveScene(Scene scene, string name, bool closeScene = true)
{
EditorSceneManager.SaveScene(scene, GetScenePath(name));
if (closeScene)
{
foreach (var sceneSetting in EditorBuildSettings.scenes)
if (sceneSetting.path == GetScenePath((name)))
return;
EditorSceneManager.CloseScene(scene, true);
EditorSceneManager.SetActiveScene(EditorSceneManager.GetSceneAt(0));
var newListOfScenes = new List<EditorBuildSettingsScene>();
newListOfScenes.Add(new EditorBuildSettingsScene(GetScenePath(name), true));
newListOfScenes.AddRange(EditorBuildSettings.scenes);
EditorBuildSettings.scenes = newListOfScenes.ToArray();
}
}
public static string GetScenePath(string name)
{
return m_ArtifactsPath + name + ".unity";
}
```
@@ -0,0 +1,16 @@
# Measure.Custom()
When you want to record samples outside of frame time, method time, or profiler markers, use a custom measurement. It
can be any value.
#### Example: Use a custom measurement to capture total allocated memory
``` csharp
[Test, Performance]
public void Test()
{
SampleGroup sampleGroup = new SampleGroup("TotalAllocatedMemory", SampleUnit.Megabyte, false);
var allocatedMemory = UnityEngine.Profiling.Profiler.GetTotalAllocatedMemoryLong() / 1048576f;
Measure.Custom(sampleGroup, allocatedMemory);
}
```
@@ -0,0 +1,120 @@
# Measure.Frames()
Records time per frame by default and provides additional properties/methods to control how the measurements are taken:
* **WarmupCount(int n)** - number of times to execute before measurements are collected. If unspecified, a default
warmup is executed for 80 ms or until at least 3 full frames have rendered, whichever is longest.
* **MeasurementCount(int n)** - number of frames to capture measurements for. If this value is not specified, as many
frames as possible are captured until approximately 500 ms has elapsed.
* **DynamicMeasurementCount(OutlierMode outlierMode)** - dynamically find a suitable measurement count based on the
margin of error of the samples. The measurements will stop once a certain amount of samples (specified by a confidence
interval) falls within an acceptable error range from the result (defined by a relative error of the mean). A default
margin of error range of 2% and a default confidence interval of 99% will be used. Statistical outliers will not be
taken into account unless different behaviour is specified through the outlierMode argument.
* **DynamicMeasurementCount(double maxRelativeError, ConfidenceLevel confidenceLevel, OutlierMode outlierMode)** -
dynamically find a suitable measurement count based on the margin of error of the samples and using the provided
confidence interval and error range.
* **DontRecordFrametime()** - disables frametime measurement.
* **ProfilerMarkers(...)** - sample profile markers per frame. Does not work for deep profiling and
`Profiler.BeginSample()`
* **SampleGroup(string name)** - name of the measurement, defaults to "Time" if unspecified.
* **Scope()** - measures frame times in a given coroutine scope. By default it uses a SampleGroup named "Time" with
Milliseconds as measurement unit. You can also create your own SampleGroup, specifying a custom name and the
measurement unit you want your results in, see [example 5](#example-5-specify-custom-samplegroup-in-the-scope).
## Limitations
* Not supported in Unity Test
Framework [Edit Mode tests](https://docs.unity3d.com/Packages/com.unity.test-framework@latest?subfolder=/manual/edit-mode-vs-play-mode-tests.html#edit-mode-tests).
#### Example 1: Simple frame time measurement using default values of at least 7 frames and default WarmupCount (see description above).
``` csharp
[UnityTest, Performance]
public IEnumerator Test()
{
...
yield return Measure.Frames().Run();
}
```
#### Example 2: Sample profile markers per frame, disable frametime measurement
If you'd like to sample profiler markers across multiple frames and don't need to record frametime, it is possible to
disable the frame time measurement.
``` csharp
[UnityTest, Performance]
public IEnumerator Test()
{
...
yield return Measure.Frames()
.ProfilerMarkers(...)
.DontRecordFrametime()
.Run();
}
```
#### Example 3: Sample frame times in a scope
``` csharp
[UnityTest, Performance]
public IEnumerator Test()
{
using (Measure.Frames().Scope())
{
yield return ...;
}
}
```
#### Example 4: Specify custom WarmupCount and MeasurementCount per frame
If you want more control, you can specify how many frames you want to measure.
``` csharp
[UnityTest, Performance]
public IEnumerator Test()
{
...
yield return Measure.Frames()
.WarmupCount(5)
.MeasurementCount(10)
.Run();
}
```
#### Example 5: Specify Custom SampleGroup in the Scope
``` csharp
[UnityTest, Performance]
public IEnumerator Test()
{
var sg = new SampleGroup("MarkerName", SampleUnit.Second);
using (Measure.Frames().Scope(sg))
{
yield return ...;
}
}
```
#### Example 6: Sample profile markers per frame with custom SampleGroups that change sample unit
``` csharp
[UnityTest, Performance]
public IEnumerator Test()
{
var sampleGroup = new SampleGroup("Name", SampleUnit.Milliseconds);
var profileMarkersSampleGroups = new []{
new SampleGroup("MarkerName", SampleUnit.Second),
new SampleGroup("MarkerName1", SampleUnit.Nanosecond)
};
yield return Measure.Frames().SampleGroup(sg).ProfilerMarkers(profileMarkersSampleGroups).Run();
...
}
```
@@ -0,0 +1,63 @@
# Measure.Method()
Executes the provided method, sampling performance using the following additional properties/methods to control how the
measurements are taken:
* **WarmupCount(int n)** - number of times to execute before measurements are collected. If unspecified, a default
warmup is executed for 100 ms or until at least 3 method executions have completed, whichever is longer.
* **MeasurementCount(int n)** - number of measurements to capture, defaults to 9 if not specified.
* **DynamicMeasurementCount(OutlierMode outlierMode)** - dynamically find a suitable measurement count based on the
margin of error of the samples. The measurements will stop once a certain amount of samples (specified by a confidence
interval) falls within an acceptable error range from the result (defined by a relative error of the mean). A default
margin of error range of 2% and a default confidence interval of 99% will be used. Statistical outliers will not be
taken into account unless different behaviour is specified through the outlierMode argument.
* **DynamicMeasurementCount(double maxRelativeError, ConfidenceLevel confidenceLevel, OutlierMode outlierMode)** -
dynamically find a suitable measurement count based on the margin of error of the samples and using the provided
confidence interval and error range.
* **IterationsPerMeasurement(int n)** - number of method executions per measurement to use. If this value is not
specified, the method is executed as many times as possible until approximately 100 ms has elapsed.
* **SampleGroup(string name)** - name of the measurement, defaults to "Time" if unspecified.
* **SampleGroup(SampleGroup sampleGroup)** - a sample group with a custom name and measurement unit. This will override
the otherwise default value of "Time".
* **GC()** - if specified, measures the total number of Garbage Collection allocation calls (known as `GC.Alloc` in Unity Profiler) as an additional sample group with ".GC()" name postfix. Also performs a full blocking garbage collection immediately before each timed region, so that a collection triggered by the measured method's own allocations does not land inside it and show up as periodic spikes across the samples. Normally that is one collection per measurement, but `SetUp` and `CleanUp` cause each of the `IterationsPerMeasurement` inner executions to be timed separately, so each of those gets its own collection - a 10-measurement run with 5 iterations per measurement and a setup action performs 50 collections, which is considerably slower. Because of all this, the times reported for a method that allocates are not directly comparable between a run with `GC()` and one without.
* **SetUp(Action action)** - is called every iteration before method execution. Setup time is not measured.
* **CleanUp(Action action)** - is called every iteration after method execution. Cleanup time is not measured.
#### Example 1: Simple method measurement using default values
``` csharp
[Test, Performance]
public void Test()
{
Measure.Method(() => { ... }).Run();
}
```
#### Example 2: Customize Measure.Method properties
``` csharp
[Test, Performance]
public void Test()
{
Measure.Method(() => { ... })
.WarmupCount(10)
.MeasurementCount(10)
.IterationsPerMeasurement(5)
.GC()
.SetUp(()=> {/*setup code*/})
.CleanUp(()=> {/*cleanup code*/})
.Run();
}
```
#### Example 3: Measure.Method, SampleGroup and ProfilerMarkers
``` csharp
[Test, Performance]
public void Test()
{
var sg = new SampleGroup("Name", SampleUnit.Microsecond);
var sgMarker = new SampleGroup("MarkerName", SampleUnit.Seconds);
Measure.Method(() => { ... }).SampleGroup(sg).ProfilerMarkers(sgMarker).Run();
}
```
@@ -0,0 +1,57 @@
# Measure.ProfilerMarkers()
Used to record profiler markers. Profiler marker timings are recorded automatically and sampled within the scope of the
`using` statement. Names should match profiler marker labels. Profiler markers are sampled once per frame. Sampling the
same profiler marker per frame will result in the sum of all invocations.
You can also create your own SampleGroups, specifying a custom name and the measurement units you want your results in,
see [example 2](#example-2-measuring-profiler-markers-in-a-scope-with-custom-samplegroups).
## Limitations
* Not supported in Unity Test
Framework [Edit Mode tests](https://docs.unity3d.com/Packages/com.unity.test-framework@latest?subfolder=/manual/edit-mode-vs-play-mode-tests.html#edit-mode-tests).
* Not supported in the Unity
Profiler's [Deep Profiling](https://docs.unity3d.com/Manual/ProfilerWindow.html#deep-profiling) mode.
* Profiler markers created using `Profiler.BeginSample()` are not supported, switch to `ProfilerMarker` if possible.
#### Example: Measuring profiler markers in a scope
``` csharp
[Test, Performance]
public void Test()
{
string[] markers =
{
"Instantiate",
"Instantiate.Copy",
"Instantiate.Produce",
"Instantiate.Awake"
};
using(Measure.ProfilerMarkers(markers))
{
...
}
}
```
#### Example 2: Measuring profiler markers in a scope with custom SampleGroups
``` csharp
[UnityTest, Performance]
public IEnumerator Test()
{
var sampleGroups = new []{
new SampleGroup("Instantiate", SampleUnit.Second),
new SampleGroup("Instantiate.Copy", SampleUnit.Nanosecond),
new SampleGroup("Instantiate.Awake", SampleUnit.Microsecond)
};
using (Measure.ProfilerMarkers(sampleGroups))
{
...
}
}
```
@@ -0,0 +1,34 @@
# Measure.Scope(string name = "Time")
Measures execution time for the scope as a single time, for both synchronous and coroutine methods. Passing the name
argument overrides the name of the created SampleGroup.
The defualt SampleGroup is named "Time" and with Milliseconds as measurement unit. You can also create your own
SampleGroup, specifying a custom name and the measurement unit you want your results in,
see [example 2](#example-2-specify-custom-samplegroup).
#### Example 1: Measuring a scope; execution time is measured for everything in the using statement
``` csharp
[Test, Performance]
public void Test()
{
using(Measure.Scope())
{
...
}
}
```
#### Example 2: Specify Custom SampleGroup
``` csharp
[Test, Performance]
public void Test()
{
var sampleGroup = new SampleGroup("Scope", SampleUnit.Microsecond);
using (Measure.Scope(sg))
{
...
}
}
```
@@ -0,0 +1,14 @@
# Taking measurements
The Performance Testing Package provides several API methods for taking measurements in your performance test, depending
on what you need to measure and how you want to do it. Include `using Unity.PerformanceTesting` at the top of your
script to access the methods.
The pages in this section detail the specifics of each measurement method with examples:
* [Measure.Method](./measure-method.md)
* [Measure.Frames](./measure-frames.md)
* [Measure.Scope](./measure-scope.md)
* [Measure.ProfilerMarkers](./measure-profile-markers.md)
* [Measure.Custom](./measure-custom.md)
@@ -0,0 +1,15 @@
# Test Attributes
This section contains a reference for attributes supported by the Performance Testing Package.
**[Performance]** - Use this with `Test` and `UnityTest` attributes. It will initialize necessary test setup for
performance tests.
**[Test]** - Non-yielding test. This type of test starts and ends within the same frame.
**[UnityTest]** - Yielding test. This is a good choice if you want to sample measurements across multiple frames. For
more on the difference between `[Test]` and `[UnityTest]`, see the Unity Test
Framework [documentation](https://docs.unity3d.com/Packages/com.unity.test-framework@1.1/manual/reference-attribute-unitytest.html).
**[Version(string version)]** - Performance tests should be versioned with every change. If not specified, the default
used is 1. This is essential when comparing results as results will vary any time the test changes.
@@ -0,0 +1,36 @@
## Output
When a test is selected in the **Test Runner** window in the Unity Editor, each performance test will have a performance
test summary. This summary includes every sample group's aggregated samples such as median, min, max, average, standard
deviation, sample count and sum of all samples.
#### Example: Performance Test Summary from Test Runner window
```
Time Microsecond Median:2018.60 Min:1903.00 Max:2819.80 Avg:2186.35 Std:368.42 SampleCount: 4 Sum: 8745.40
```
## The Performance Test Report
The Performance Test Report (**Window > General > Performance Test Report**) shows a detailed breakdown of individual
test runs. This can be used to assess the stability of each test. It provides a visualization of each individual sample
recorded within a sample group along with summary statistics for the selected test.
The Performance Test Report is split into two views: the *test view* and the *sample group view*.
**Test View:** Provides a list of all tests. Tests are separated by class names. Each of the columns can be clicked to
sort the view. Column values show the sample group with highest deviation.
* *Name* - Name of the test.
* *Deviation* - The deviation is calculated by dividing the standard deviation by the median for a sample group. It
shows the sample group with the highest 'deviation' value. Useful for defining stability of the test.
* *Standard Deviation* - Standard deviation of the samples in a sample group. It shows the sample group with the highest
standard deviation.
**Sample Group View:** Visualizes sample groups for the test selected in the Test View. Provides:
* Sample group summary displaying the min, max, and median values for a given sample group.
* Samples displayed in a bar chart, ordered by time, with a blue line indicating the median.
* Box plot showing upper (75%) and lower (25%) quartiles, min, max and median of the samples for a given sample group.
![Performance test report](images/graphtool.png)
@@ -0,0 +1,264 @@
# Writing a simple test
This example uses `Measure.Method` to measure the performance of Vector2 operations. This executes the provided method
and samples performance. Increasing `MeasurementCount` from the default of 7 to 20 improves performance test stability.
You can execute a `Vector2.MoveTowards` test in Edit Mode or Play Mode.
``` csharp
[Test, Performance]
public void Vector2_operations()
{
var a = Vector2.one;
var b = Vector2.zero;
Measure.Method(() =>
{
Vector2.MoveTowards(a, b, 0.5f);
Vector2.ClampMagnitude(a, 0.5f);
Vector2.Reflect(a, b);
Vector2.SignedAngle(a, b);
})
.MeasurementCount(20)
.Run();
}
```
To view the results, go to **Window > General > Performance Test Report**.
![Performance test example01](images/example01.png)
In this example, the results show that the first method execution took five times longer than the subsequent methods,
and those subsequent method executions were unstable. Also, you can't tell from these test results how long it took for
each Vector2 operation to execute.
## Improving test stability
Now we'll look at how to improve the stability of our test. Instability can occur at the beginning of a test for several
reasons, such as entering Play Mode or method initialization, because the tested method is quite fast and more sensitive
to other running background processes.
To improve stability, use `WarmupCount(n)`. This allows you to execute methods before recording data, so Unity doesn't
record method initialization. The simplest way to increase test execution time is to repeat the method in a loop.
Avoid having measurements that are less than 1ms because they are usually more sensitive to unstable environments.
To help you track the execution time for each operation, split the Vector2 operations into several tests. Often, when
writing tests, we use setup and clean up methods to isolate the test environment. However, in this case, methods are
isolated and do not affect other methods, so we don't need a cleanup or setup.
The following code example shows a performance test for the `Vector2.MoveTowards` operation. Other Vector2 performance
tests are identical.
``` csharp
[Test, Performance]
public void Vector2_MoveTowards()
{
Measure.Method(() =>
{
Vector2.MoveTowards(Vector2.one, Vector2.zero, 0.5f);
})
.WarmupCount(5)
.IterationsPerMeasurement(10000)
.MeasurementCount(20)
.Run();
}
```
With 100000 iterations in this test, we see a small fluctuation in method execution time but the standard deviation is
low, which means the test is reasonably stable.
![Performance test example02](images/example02.png)
## Measure a Play Mode only method
To measure a method that only runs in Play Mode (for example `Physics.Raycast`), you can use `Measure.Frames()`, which
records time per frame by default. To only measure `Physics.Raycast` time, you can disable frame time measurements with
`DontRecordFrametime` and just measure the `Physics.Raycast` profiler marker.
This test creates objects that you need to dispose of at the end of each test, because multiple unnecessary objects can
affect the next test results. Use the SetUp method to create GameObjects, and the TearDown method to destroy the created
GameObjects after each test.
``` csharp
[SetUp]
public void SetUp()
{
for (int i = 0; i < 100; ++i)
{
GameObject raycaster = new GameObject("raycast", typeof(Raycast));
raycaster.transform.SetParent(_parent.transform);
}
}
[UnityTest, Performance]
public IEnumerator Physics_RaycastTests()
{
string profilierMarker = "Physics.Raycast";
yield return Measure.Frames()
.WarmupCount(3)
.DontRecordFrametime()
.MeasurementCount(10)
.ProfilerMarkers(profilierMarker)
.Run();
}
public class Raycast : MonoBehaviour
{
private void Update()
{
RaycastHit hit;
bool ray = Physics.Raycast(
transform.position,
Vector3.forward,
out hit,
Mathf.Infinity);
}
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(_parent);
}
```
To record your own measurements, create a new sample group and record a custom metric. The following example measures
`Allocated` and `Reserved` memory.
``` csharp
[Test, Performance]
public void Empty()
{
var allocated = new SampleGroup("TotalAllocatedMemory", SampleUnit.Megabyte);
var reserved = new SampleGroup("TotalReservedMemory", SampleUnit.Megabyte);
using (Measure.Scope())
{
Measure.Custom(allocated, UnityEngine.Profiling.Profiler.GetTotalAllocatedMemoryLong() / 1048576f);
Measure.Custom(reserved, UnityEngine.Profiling.Profiler.GetTotalReservedMemoryLong() / 1048576f);
}
}
```
Before you start to collect package performance data, make sure the tests you run locally are stable (the data set
deviation is <5%). In the **Performance Test Report** window, ensure the test isn't fluctuating and that the results
between runs are similar.
Results of performance tests run on a local machine can be significantly different to previous test runs because of
other applications running in the background, CPU overheating, or CPU boosting. Make sure that CPU intensive
applications are turned off where possible. You can disable CPU boost in the BIOS or with third-party software such as
Real Temp.
For comparing performance data between runs, use
the [Unity Performance Benchmark Reporter](https://github.com/Unity-Technologies/PerformanceBenchmarkReporter/wiki),
which provides a graphical HTML report that enables you to compare performance metric baselines and subsequent
performance metrics.
## Further examples
#### Example 1: Measure Frame Time For Scene
``` csharp
[UnityTest, Performance, Version("4")]
public IEnumerator MainSceneFrameTime_StartPosition()
{
SceneManager.LoadScene("Demo", LoadSceneMode.Single);
// Measure initial time of first 25 frames after loading the scene
using(Measure.Frames().Scope("FrameTime.FirstFramesAfterLoadingScene"))
{
for (var i = 0; i < 25; i++)
{
yield return null;
}
}
// Measure frame times for ten seconds during rest of the "Demo" scene
using (Measure.Frames().Scope("FrameTime.Main"))
{
yield return new WaitForSeconds(10);
}
}
```
#### Example 2: Measure execution time to serialize simple object to JSON
``` csharp
[Test, Performance, Version("2")]
public void Serialize_SimpleObject()
{
var obj = new SimpleObject();
obj.Init();
Measure.Method(() => JsonUtility.ToJson(obj)).Run();
}
[Serializable]
public class SimpleObject
{
public int IntField;
public string StringField;
public float FloatField;
public bool BoolField;
[Serializable]
public struct NestedStruct
{
public int A, B;
}
public NestedStruct Str;
public Vector3 Position;
public void Init()
{
IntField = 1;
StringField = "Test";
FloatField = 2.0f;
BoolField = false;
Str.A = 15;
Str.B = 20;
}
}
```
#### Example 3: Measure execution time to create 5000 simple cubes
``` csharp
string[] markers =
{
"Instantiate",
"Instantiate.Copy",
"Instantiate.Produce",
"Instantiate.Awake"
};
[Test, Performance]
public void Instantiate_CreateCubes()
{
using (Measure.ProfilerMarkers(markers))
{
using(Measure.Scope())
{
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
for (var i = 0; i < 5000; i++)
{
UnityEngine.Object.Instantiate(cube);
}
}
}
}
```
#### Example 4: Custom measurement to capture total allocated and reserved memory
``` csharp
[Test, Performance, Version("1")]
public void Measure_Empty()
{
var allocated = new SampleGroup("TotalAllocatedMemory", SampleUnit.Megabyte);
var reserved = new SampleGroup("TotalReservedMemory", SampleUnit.Megabyte);
Measure.Custom(allocated, UnityEngine.Profiling.Profiler.GetTotalAllocatedMemoryLong() / 1048576f);
Measure.Custom(reserved, UnityEngine.Profiling.Profiler.GetTotalReservedMemoryLong() / 1048576f);
}
```