### Measure Profiler Markers with Custom SampleGroups Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/measure-profile-markers.md This example demonstrates measuring profiler markers with custom SampleGroups, allowing you to specify custom names and measurement units (e.g., Second, Nanosecond, Microsecond) for the results. ```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)) { ... } } ``` -------------------------------- ### Performance Test Summary Example Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/viewing-results.md This is an example of the aggregated sample data displayed for a performance test in the Test Runner window. It includes median, min, max, average, standard deviation, sample count, and sum of all samples. ```text Time Microsecond Median:2018.60 Min:1903.00 Max:2819.80 Avg:2186.35 Std:368.42 SampleCount: 4 Sum: 8745.40 ``` -------------------------------- ### Measure Frame Time for Scene Loading and Gameplay Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/writing-tests.md Measures frame times in two phases: initial frames after scene loading and during gameplay for a specified duration. Ensures the scene is loaded before starting measurements. ```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); } } ``` -------------------------------- ### Implement IPrebuildSetup for Performance Tests Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/index.md Implement the IPrebuildSetup interface to execute code before entering play mode or running a player. This is useful for generating assets or setting up test environments. ```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() { ... } } ``` -------------------------------- ### Method Measurement with Custom Sample Groups and Profiler Markers Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/measure-method.md Measure method performance and assign custom sample groups with specific units, and integrate Unity Profiler markers for more detailed analysis. This is useful for correlating performance with specific in-game events. ```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(); } ``` -------------------------------- ### Measure Instantiation Time for Cubes Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/writing-tests.md Measures the execution time for instantiating 5000 primitive cubes using profiling markers. ```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); } } } } ``` -------------------------------- ### Simple Method Measurement Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/measure-method.md Use this snippet to perform a basic performance measurement of a method using default settings. Ensure the method is annotated with [Test, Performance]. ```csharp [Test, Performance] public void Test() { Measure.Method(() => { ... }).Run(); } ``` -------------------------------- ### Run Performance Tests with Custom Output Paths Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/cmd-line-args.md Use this command to execute performance tests in batch mode, specifying custom paths for both NUnit XML results and performance test JSON results. ```bash Unity.exe -runTests -batchmode -projectPath PATH_TO_YOUR_PROJECT -testResults C:\temp\results.xml -perfTestResults C:\temp\perfResults.json ``` -------------------------------- ### Sample Profiler Markers with Custom SampleGroups Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/measure-frames.md Samples profiler markers per frame using custom SampleGroups, allowing for different measurement units for each marker. Ensure the test method is marked with [UnityTest, Performance]. ```csharp using System.Collections; using NUnit.Framework; using UnityEngine.TestTools; public class PerformanceTests { [UnityTest, Performance] public IEnumerator Test() { var sg = 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(); // ... } } ``` -------------------------------- ### Specify Custom Warmup and Measurement Counts Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/measure-frames.md Allows explicit control over the number of warmup frames and measurement frames. Ensure the test method is marked with [UnityTest, Performance]. ```csharp using System.Collections; using NUnit.Framework; using UnityEngine.TestTools; public class PerformanceTests { [UnityTest, Performance] public IEnumerator Test() { // ... yield return Measure.Frames() .WarmupCount(5) .MeasurementCount(10) .Run(); } } ``` -------------------------------- ### Create, Save, and Add Scenes to Build Settings in Unity Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/index.md Use EditorSceneManager to create new scenes additively, save them, and add them to the build settings. This is useful for managing test scenes or performance-critical environments. ```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(); 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"; } ``` -------------------------------- ### Simple Frame Time Measurement Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/measure-frames.md Records frame times using default warmup and measurement counts. Ensure the test method is marked with [UnityTest, Performance]. ```csharp using System.Collections; using NUnit.Framework; using UnityEngine.TestTools; public class PerformanceTests { [UnityTest, Performance] public IEnumerator Test() { // ... yield return Measure.Frames().Run(); } } ``` -------------------------------- ### Record Total Allocated Memory with Measure.Custom() Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/measure-custom.md Use this snippet to capture the total allocated memory in megabytes. Ensure the SampleGroup is correctly configured with the desired unit and name. ```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); } ``` -------------------------------- ### Customized Method Measurement Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/measure-method.md Customize performance measurement parameters like warmup count, measurement count, iterations per measurement, GC allocation tracking, and setup/cleanup actions. This provides fine-grained control over the measurement process. ```csharp [Test, Performance] public void Test() { Measure.Method(() => { ... }) .WarmupCount(10) .MeasurementCount(10) .IterationsPerMeasurement(5) .GC() .SetUp(()=> {/*setup code*/}) .CleanUp(()=> {/*cleanup code*/}) .Run(); } ``` -------------------------------- ### Specify Custom SampleGroup for Measure.Scope Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/measure-scope.md Creates a custom SampleGroup with a specified name and measurement unit (e.g., Microsecond) for measuring execution time within the scope. ```csharp var sampleGroup = new SampleGroup("Scope", SampleUnit.Microsecond); using (Measure.Scope(sg)) { ... } ``` -------------------------------- ### Sample Profiler Markers and Disable Frametime Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/measure-frames.md Samples profiler markers per frame while disabling frametime measurement. Useful when only profiler data is needed. Ensure the test method is marked with [UnityTest, Performance]. ```csharp using System.Collections; using NUnit.Framework; using UnityEngine.TestTools; public class PerformanceTests { [UnityTest, Performance] public IEnumerator Test() { // ... yield return Measure.Frames() .ProfilerMarkers(...) .DontRecordFrametime() .Run(); } } ``` -------------------------------- ### Specify Custom SampleGroup in Scope Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/measure-frames.md Measures frame times within a scope using a custom SampleGroup with a specified name and unit. Ensure the test method is marked with [UnityTest, Performance]. ```csharp using System.Collections; using NUnit.Framework; using UnityEngine.TestTools; public class PerformanceTests { [UnityTest, Performance] public IEnumerator Test() { var sg = new SampleGroup("MarkerName", SampleUnit.Second); using (Measure.Frames().Scope(sg)) { yield return ...; } } } ``` -------------------------------- ### Measure Custom Memory Metrics Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/writing-tests.md Records custom metrics for 'TotalAllocatedMemory' and 'TotalReservedMemory' in megabytes. Use 'Measure.Scope()' to define the measurement block and 'Measure.Custom()' to record the values. ```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); } } ``` -------------------------------- ### Measure Profiler Markers in a Scope Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/measure-profile-markers.md Use this snippet to measure profiler markers by providing an array of marker names. The timings are automatically recorded within the `using` scope. ```csharp [Test, Performance] public void Test() { string[] markers = { "Instantiate", "Instantiate.Copy", "Instantiate.Produce", "Instantiate.Awake" }; using(Measure.ProfilerMarkers(markers)) { ... } } ``` -------------------------------- ### SampleGroup Class Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/classes.md Represents a group of samples with the same purpose, sharing a name, sample unit, and whether an increase is considered better. ```APIDOC ## Class SampleGroup Represents a group of samples with the same purpose that share a name, sample unit and whether an increase is better. ### Parameters - **Name** (string) - Optional - Name of the measurement. If unspecified, "Time" is used as the default name. - **Unit** (enum) - Optional - Unit of the measurement to report samples in. Possible values are: Nanosecond, Microsecond, Millisecond, Second, Byte, Kilobyte, Megabyte, Gigabyte. - **IncreaseIsBetter** (boolean) - Optional - 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. ``` -------------------------------- ### Measure Total Allocated and Reserved Memory Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/writing-tests.md Captures the total allocated and reserved memory in megabytes using custom measurements. ```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); } ``` -------------------------------- ### Measure Scope Execution Time Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/measure-scope.md Measures the execution time for everything within the using statement. The default SampleGroup is named 'Time' and uses Milliseconds as the measurement unit. ```csharp using(Measure.Scope()) { ... } ``` -------------------------------- ### Measure Execution Time to Serialize Simple Object to JSON Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/writing-tests.md Measures the execution time of serializing a simple object to JSON using `JsonUtility.ToJson`. The `SimpleObject` class and its nested struct are defined for this purpose. ```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; } } ``` -------------------------------- ### Improve Vector2 MoveTowards Test Stability Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/writing-tests.md Improves the stability of a performance test for `Vector2.MoveTowards` by using `WarmupCount` and `IterationsPerMeasurement`. This helps to reduce fluctuations caused by initialization and background processes. ```csharp using UnityEngine; using NUnit.Framework; using Unity.PerformanceTesting; public class Vector2MoveTowardsTests { [Test, Performance] public void Vector2_MoveTowards() { Measure.Method(() => { Vector2.MoveTowards(Vector2.one, Vector2.zero, 0.5f); }) .WarmupCount(5) .IterationsPerMeasurement(10000) .MeasurementCount(20) .Run(); } } ``` -------------------------------- ### Measure Frame Times in a Scope Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/measure-frames.md Measures frame times within a specified coroutine scope. By default, it uses a SampleGroup named "Time" with Milliseconds as the measurement unit. Ensure the test method is marked with [UnityTest, Performance]. ```csharp using System.Collections; using NUnit.Framework; using UnityEngine.TestTools; public class PerformanceTests { [UnityTest, Performance] public IEnumerator Test() { using (Measure.Frames().Scope()) { yield return ...; } } } ``` -------------------------------- ### Measure Play Mode Physics.Raycast Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/writing-tests.md Measures the time spent on Physics.Raycast in Play Mode by disabling frame time recording and focusing on specific profiler markers. Ensure GameObjects are disposed of in TearDown to prevent affecting subsequent tests. ```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); } ``` -------------------------------- ### Measure Vector2 Operations Performance Source: https://github.com/needle-mirror/com.unity.test-framework.performance/blob/master/Documentation~/writing-tests.md Measures the performance of multiple Vector2 operations. Increase `MeasurementCount` for better stability. This test can be run in Edit or Play Mode. ```csharp using UnityEngine; using NUnit.Framework; using Unity.PerformanceTesting; public class Vector2Tests { [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(); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.