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,10 @@
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("Unity.PerformanceTesting")]
[assembly: InternalsVisibleTo("Unity.PerformanceTesting.Editor")]
[assembly: InternalsVisibleTo("Unity.PerformanceTesting.Tests.Runtime")]
[assembly: InternalsVisibleTo("Unity.GraphTools.Foundation.Testing.Editor")]
[assembly: AssemblyVersion("3.4.2")]
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ac464bc14bd17cc4ca2e8f909ca4f061
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d2bd35c14da30b94c81ec15c7db30136
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,85 @@
using System;
using System.Collections;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using Unity.PerformanceTesting.Data;
using Unity.PerformanceTesting.Runtime;
using UnityEngine.TestTools;
namespace Unity.PerformanceTesting
{
/// <summary>
/// Test attribute to specify a performance test. It will add category "Performance" to test properties.
/// Optionally, a performance regression threshold can be specified, to be used at the test result endpoint.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class PerformanceAttribute : CategoryAttribute, IOuterUnityTestAction, IApplyToTest
{
/// <summary>
/// Adds performance attribute to a test method.
/// </summary>
public PerformanceAttribute()
: base("Performance") { }
/// <summary>
/// Performance regression threshold.
/// </summary>
public double Threshold { get; } = PerformanceTest.DefaultThresholdValue;
/// <summary>
/// Adds performance attribute to a test method with a performance regression threshold.
/// </summary>
/// <param name="threshold">A performance regression threshold to associate for the given test, taken into account at the result endpoint. The value represents a multiple of the result. Only positive values are considered valid. If the value is invalid, the property will not be serialized/sent to the result endpoint.</param>
public PerformanceAttribute(double threshold) : base("Performance")
{
Threshold = threshold;
}
/// <summary>
/// Executed before a test execution.
/// </summary>
/// <param name="test">Test to execute.</param>
/// <returns>Enumerable collection of actions to perform before test setup.</returns>
public IEnumerator BeforeTest(ITest test)
{
if (RunSettings.Instance == null)
{
RunSettings.Instance = ResourcesLoader.Load<RunSettings>(Utils.RunSettings, Utils.PlayerPrefKeySettingsJSON);
}
// domain reload will cause this method to be hit multiple times
// active performance test is serialized and survives reloads
if (PerformanceTest.Active == null)
{
PerformanceTest.StartTest(test);
yield return null;
}
}
/// <summary>
/// Executed after a test execution.
/// </summary>
/// <param name="test">Executed test.</param>
/// <returns>Enumerable collection of actions to perform after test teardown.</returns>
public IEnumerator AfterTest(ITest test)
{
PerformanceTest.EndTest(test);
yield return null;
}
/// <summary>
/// Used to apply the Threshold property to the Test's Properties
/// </summary>
/// <param name="test">An NUnit test</param>
public new void ApplyToTest(Test test)
{
if (Threshold > PerformanceTest.ThresholdSerializationCutOff)
{
test.Properties.Add("Threshold", Threshold);
}
base.ApplyToTest(test);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f97b05006f7e8f34bbde1823b11b5308
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
namespace Unity.PerformanceTesting
{
internal class RequiredMemberAttribute
#if UNITY_2021_1_OR_NEWER
: UnityEngine.Scripting.RequiredMemberAttribute
#else
: System.Attribute
#endif
{
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0d9f444a464203c478024791eff61732
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,37 @@
using System;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
namespace Unity.PerformanceTesting
{
/// <summary>
/// Test attribute to specify test version.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class VersionAttribute : NUnitAttribute, IApplyToTest
{
/// <summary>
/// Test version.
/// </summary>
public string Version { get; }
/// <summary>
/// Adds attribute to specify test version.
/// </summary>
/// <param name="version">Version of the test.</param>
public VersionAttribute(string version)
{
Version = version;
}
/// <summary>
/// Used by NUnit to apply version to properties.
/// </summary>
/// <param name="test">An NUnit test to apply the version property to.</param>
public void ApplyToTest(Test test)
{
test.Properties.Add("Version", this);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3ea2d7f3aee148a48bf80eafd7113fe0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0369bc643b4a11246a869e582c0f275a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,31 @@
using System;
namespace Unity.PerformanceTesting.Data
{
/// <summary>
/// Represents information about Editor version.
/// </summary>
[Serializable]
public class Editor
{
/// <summary>
/// Full editor version including changeset.
/// </summary>
[RequiredMember] public string Version;
/// <summary>
/// Branch name from which the editor was built.
/// </summary>
[RequiredMember] public string Branch;
/// <summary>
/// Changeset 12 characters long.
/// </summary>
[RequiredMember] public string Changeset;
/// <summary>
/// Editor version datetime in Unix Epoch milliseconds format.
/// </summary>
[RequiredMember] public int Date;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 634ca08416be7e446b17074b7a8d85ef
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,46 @@
using System;
namespace Unity.PerformanceTesting.Data
{
/// <summary>
/// Represents information about Hardware.
/// </summary>
[Serializable]
public class Hardware
{
/// <summary>
/// Operating system.
/// </summary>
[RequiredMember] public string OperatingSystem;
/// <summary>
/// Device model.
/// </summary>
[RequiredMember] public string DeviceModel;
/// <summary>
/// Device name.
/// </summary>
[RequiredMember] public string DeviceName;
/// <summary>
/// Processor type name.
/// </summary>
[RequiredMember] public string ProcessorType;
/// <summary>
/// Processor thread count.
/// </summary>
[RequiredMember] public int ProcessorCount;
/// <summary>
/// Graphics device name.
/// </summary>
[RequiredMember] public string GraphicsDeviceName;
/// <summary>
/// System Memory size in MegaBytes.
/// </summary>
[RequiredMember] public int SystemMemorySizeMB;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: eecaaae1ce1cb6d4191f80484e152f46
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
namespace Unity.PerformanceTesting.Data
{
/// <summary>
/// Represents a performance test result.
/// </summary>
[Serializable]
public class PerformanceTestResult
{
/// <summary>
/// Full test name.
/// </summary>
[RequiredMember] public string Name;
/// <summary>
/// Test script name.
/// </summary>
[RequiredMember] public string ClassName;
/// <summary>
/// Test method name.
/// </summary>
[RequiredMember] public string MethodName;
/// <summary>
/// Test version.
/// </summary>
[RequiredMember] public string Version;
/// <summary>
/// Categories.
/// </summary>
[RequiredMember] public List<string> Categories = new List<string>();
/// <summary>
/// Groups of performance samples.
/// </summary>
[RequiredMember] public List<SampleGroup> SampleGroups = new List<SampleGroup>();
/// <summary>
/// Performance regression threshold. A negative value indicates it is not to be used/transmitted.
/// </summary>
public double Threshold = PerformanceTest.DefaultThresholdValue;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: eee38b155cc303447b8c478d95185d54
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,123 @@
using System;
namespace Unity.PerformanceTesting.Data
{
/// <summary>
/// Represents player settings of a performance test, sampled at the beginning of a test run.
/// </summary>
[Serializable]
public class Player
{
/// <summary>
/// True if the player is a Development build. False if the player is a Release build.
/// </summary>
[RequiredMember] public bool Development;
/// <summary>
/// Screen resolution width.
/// </summary>
[RequiredMember] public int ScreenWidth;
/// <summary>
/// Screen resolution height.
/// </summary>
[RequiredMember] public int ScreenHeight;
/// <summary>
/// Screen refresh rate.
/// </summary>
[RequiredMember] public int ScreenRefreshRate;
/// <summary>
/// Whether the player is in fullscreen or windowed modes.
/// </summary>
[RequiredMember] public bool Fullscreen;
/// <summary>
/// The number of VSyncs that should pass between each frame. Use 'Don't Sync' (0) to not wait for VSync. Value must be 0, 1, 2, 3, or 4.
/// </summary>
[RequiredMember] public int Vsync;
/// <summary>
/// Anti aliasing.
/// </summary>
[RequiredMember] public int AntiAliasing;
/// <summary>
/// Whether player is in batchmode or not.
/// </summary>
[RequiredMember] public bool Batchmode;
/// <summary>
/// Render threading mode.
/// </summary>
[RequiredMember] public string RenderThreadingMode;
/// <summary>
/// Whether the render threading mode is multithreaded or not.
/// </summary>
[RequiredMember] public bool MtRendering;
/// <summary>
/// Whether the render threading mode uses Graphics Jobs or not.
/// </summary>
[RequiredMember] public bool GraphicsJobs;
/// <summary>
/// Whether the Unity Graphics Kernel is enabled or not.
/// </summary>
[RequiredMember] public bool UnityGraphicsKernel;
/// <summary>
/// Whether GPU skinning is enabled or not.
/// </summary>
[RequiredMember] public bool GpuSkinning;
/// <summary>
/// String representation of players RuntimePlatform.
/// </summary>
[RequiredMember] public string Platform;
/// <summary>
/// Color space.
/// </summary>
[RequiredMember] public string ColorSpace;
/// <summary>
/// Anisotropic filtering.
/// </summary>
[RequiredMember] public string AnisotropicFiltering;
/// <summary>
/// Blend weights.
/// </summary>
[RequiredMember] public string BlendWeights;
/// <summary>
/// Graphics API.
/// </summary>
[RequiredMember] public string GraphicsApi;
// strings because their enums are editor only.
/// <summary>
/// Scripting backend.
/// </summary>
[RequiredMember] public string ScriptingBackend;
/// <summary>
/// Android target SDK version.
/// </summary>
[RequiredMember] public string AndroidTargetSdkVersion;
/// <summary>
/// Android build system.
/// </summary>
[RequiredMember] public string AndroidBuildSystem;
/// <summary>
/// Build target.
/// </summary>
[RequiredMember] public string BuildTarget;
/// <summary>
/// Stereo rendering path.
/// </summary>
[RequiredMember] public string StereoRenderingPath;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 451a2d412ec85674b870cfe148524e5c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,33 @@
namespace Unity.PerformanceTesting.Data
{
/// <summary>
/// Represents Project version.
/// </summary>
public class Project
{
/// <summary>
/// Name of the project.
/// </summary>
[RequiredMember] public string Name;
/// <summary>
/// Version of the project unrelated to changeset e.g. package version.
/// </summary>
[RequiredMember] public string Version;
/// <summary>
/// Commit branch.
/// </summary>
[RequiredMember] public string Branch;
/// <summary>
/// Commit changeset.
/// </summary>
[RequiredMember] public string Changeset;
/// <summary>
/// Commit datetime in Unix Epoch milliseconds format.
/// </summary>
[RequiredMember] public int Date;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 601d7eee390860c4e80380ed9ff5e296
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
namespace Unity.PerformanceTesting.Data
{
/// <summary>
/// Represents a performance test run.
/// </summary>
[Serializable]
public class Run
{
/// <summary>
/// Test Suite.
/// </summary>
[RequiredMember] public string TestSuite;
/// <summary>
/// Test run start datetime in Unix Epoch milliseconds format.
/// </summary>
[RequiredMember] public long Date;
/// <summary>
/// Player settings.
/// </summary>
[RequiredMember] public Player Player;
/// <summary>
/// Hardware information.
/// </summary>
[RequiredMember] public Hardware Hardware;
/// <summary>
/// Editor version.
/// </summary>
[RequiredMember] public Editor Editor;
/// <summary>
/// Package dependencies.
/// </summary>
[RequiredMember] public List<string> Dependencies = new List<string>();
/// <summary>
/// List of performance test results.
/// </summary>
[RequiredMember] public List<PerformanceTestResult> Results = new List<PerformanceTestResult>();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2cea93e2f05193940bf0b8deca0c3898
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,68 @@
using System;
using System.Runtime.Serialization;
using Unity.PerformanceTesting.Runtime;
using UnityEngine;
namespace Unity.PerformanceTesting.Data
{
/// <summary>
/// Settings store
/// @TODO make it public along with guidelines of how and when to use
/// @TODO add a property bag
/// </summary>
[Serializable]
internal class RunSettings : IDeserializationCallback
{
public RunSettings(params string[] args)
{
if (int.TryParse(Utils.GetArg(args, "-performance-measurement-count"), out var measurementMultiplier))
{
MeasurementCount = measurementMultiplier;
}
}
private static RunSettings m_Instance;
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void ResetStaticsOnLoad()
{
m_Instance = null;
}
#endif
/// <summary>
/// Singleton instance of settings.
/// </summary>
public static RunSettings Instance
{
get
{
if (m_Instance == null)
{
m_Instance = ResourcesLoader.Load<RunSettings>(Utils.RunSettings, Utils.PlayerPrefKeySettingsJSON);
}
return m_Instance;
}
set { m_Instance = value; }
}
/// <summary>
/// Measurement counts will be overriden by specified value when using Measure.Method and Measure.Frames.
/// </summary>
public int MeasurementCount = -1;
/// <summary>
/// Validates the deserialized object.
/// </summary>
/// <param name="sender">The object that initiated the deserialization process.</param>
public void OnDeserialization(object sender)
{
if (MeasurementCount < -1)
{
throw new SerializationException("MeasurementCount cannot be negative, except for the initial value of -1.");
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 60f3b660212a40e7afb5bf15edcd64f2
timeCreated: 1617790852
@@ -0,0 +1,91 @@
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Unity.PerformanceTesting.Exceptions;
namespace Unity.PerformanceTesting.Data
{
/// <summary>
/// Represents a group of samples for a performance test that share a common name and unit.
/// </summary>
[Serializable]
public class SampleGroup : IDeserializationCallback
{
/// <summary>
/// Name of the sample group.
/// </summary>
public string Name;
/// <summary>
/// Measurement unit.
/// </summary>
public SampleUnit Unit;
/// <summary>
/// Whether the measurement is inverted and increase is positive.
/// </summary>
public bool IncreaseIsBetter;
/// <summary>
/// List of samples.
/// </summary>
public List<double> Samples = new List<double>();
/// <summary>
/// Minimum value of samples.
/// </summary>
public double Min;
/// <summary>
/// Maximum value of samples.
/// </summary>
public double Max;
/// <summary>
/// Median value of samples.
/// </summary>
public double Median;
/// <summary>
/// Average value of samples.
/// </summary>
public double Average;
/// <summary>
/// Standard deviation of samples.
/// </summary>
public double StandardDeviation;
/// <summary>
/// Sum of samples.
/// </summary>
public double Sum;
/// <summary>
/// Creates a sample group without initializing values.
/// </summary>
public SampleGroup(){}
/// <summary>
/// Creates a sample group with provided arguments.
/// </summary>
/// <param name="name">Sample group name.</param>
/// <param name="unit">Measurement unit.</param>
/// <param name="increaseIsBetter">Whether the measurement is inverted and increase is positive.</param>
/// <exception cref="PerformanceTestException">Exception thrown when invalid name is used.</exception>
public SampleGroup(string name, SampleUnit unit, bool increaseIsBetter)
{
Name = name;
Unit = unit;
IncreaseIsBetter = increaseIsBetter;
if (string.IsNullOrEmpty(name))
{
throw new PerformanceTestException("Sample group name is empty. Please assign a valid name.");
}
}
/// <summary>
/// Validates the deserialized object.
/// </summary>
/// <param name="sender">The object that initiated the deserialization process.</param>
public void OnDeserialization(object sender)
{
if (string.IsNullOrEmpty(Name))
{
throw new PerformanceTestException("Sample group name is empty. Please assign a valid name.");
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ea30bf37a2f167f4aa4086531e8d5b03
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,85 @@
using System;
namespace Unity.PerformanceTesting
{
/// <summary>
/// Measurement unit used for sample groups.
/// </summary>
public enum SampleUnit
{
/// <summary>
/// Nanoseconds.
/// </summary>
Nanosecond,
/// <summary>
/// Microseconds.
/// </summary>
Microsecond,
/// <summary>
/// Milliseconds.
/// </summary>
Millisecond,
/// <summary>
/// Seconds.
/// </summary>
Second,
/// <summary>
/// Bytes.
/// </summary>
Byte,
/// <summary>
/// Kilobytes.
/// </summary>
Kilobyte,
/// <summary>
/// Megabytes.
/// </summary>
Megabyte,
/// <summary>
/// Gigabytes.
/// </summary>
Gigabyte,
/// <summary>
/// Undefined, represents any other unit we don't have by default. When using it make sure your sample group name represents the measurement.
/// </summary>
Undefined
}
static class SampleUnitExtensions
{
public static string ShortName(this SampleUnit s)
{
switch (s)
{
case SampleUnit.Nanosecond:
return "ns";
case SampleUnit.Microsecond:
return "μs";
case SampleUnit.Millisecond:
return "ms";
case SampleUnit.Second:
return "s";
case SampleUnit.Byte:
return "b";
case SampleUnit.Kilobyte:
return "kb";
case SampleUnit.Megabyte:
return "mb";
case SampleUnit.Gigabyte:
return "gb";
case SampleUnit.Undefined:
return "";
default:
throw new ArgumentOutOfRangeException(nameof(s), s, null);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8a61e4b297fe5f94cb16e6f77a71892c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,120 @@
using System;
using System.Diagnostics;
using Unity.PerformanceTesting.Exceptions;
using Unity.PerformanceTesting.Measurements;
using Unity.PerformanceTesting.Runtime;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Unity.PerformanceTesting
{
/// <summary>
/// Enables measuring of performance metrics during a performance test.
/// </summary>
public static class Measure
{
/// <summary>
/// Saves provided value as a performance measurement.
/// </summary>
/// <param name="sampleGroup">The sample group to save the value to.</param>
/// <param name="value">Value to be saved.</param>
public static void Custom(SampleGroup sampleGroup, double value)
{
VerifyValue(sampleGroup.Name, value);
var activeSampleGroup = PerformanceTest.GetSampleGroup(sampleGroup.Name);
if (activeSampleGroup == null)
{
PerformanceTest.AddSampleGroup(sampleGroup);
activeSampleGroup = sampleGroup;
}
activeSampleGroup.Samples.Add(value);
}
/// <summary>
/// Saves provided value as a performance measurement.
/// </summary>
/// <param name="name">The name of the sample group to save the value to.</param>
/// <param name="value">Value to be saved.</param>
public static void Custom(string name, double value)
{
VerifyValue(name, value);
var activeSampleGroup = PerformanceTest.GetSampleGroup(name);
if (activeSampleGroup == null)
{
activeSampleGroup = new SampleGroup(name);
PerformanceTest.AddSampleGroup(activeSampleGroup);
}
activeSampleGroup.Samples.Add(value);
}
static void VerifyValue(string name, double value)
{
if (double.IsNaN(value))
throw new PerformanceTestException(
$"Trying to record value which is not a number for sample group: {name}");
}
/// <summary>
/// Measures execution time for the given scope as a single time.
/// </summary>
/// <param name="name">Name to use for the sample group.</param>
/// <returns>IDisposable <see cref="ScopeMeasurement"/> on which you should call the <see cref="ScopeMeasurement.Dispose"/> method to stop measurement.</returns>
public static ScopeMeasurement Scope(string name = "Time")
{
return new ScopeMeasurement(name);
}
/// <summary>
/// Measures execution time for the given scope as a single time.
/// </summary>
/// <param name="sampleGroup">Sample group to use to save samples to.</param>
/// <returns>IDisposable <see cref="ScopeMeasurement"/> on which you should call the <see cref="ScopeMeasurement.Dispose"/> method to stop measurement.</returns>
public static ScopeMeasurement Scope(SampleGroup sampleGroup)
{
return new ScopeMeasurement(sampleGroup);
}
/// <summary>
/// Measures profiler markers for the given scope.
/// </summary>
/// <param name="profilerMarkerLabels">List of profiler marker names.</param>
/// <returns>A ProfilerMeasurement instance configured according to the given arguments.</returns>
public static ProfilerMeasurement ProfilerMarkers(params string[] profilerMarkerLabels)
{
return new ProfilerMeasurement(profilerMarkerLabels);
}
/// <summary>
/// Measures profiler markers for the given scope.
/// </summary>
/// <param name="sampleGroups">List of SampleGroups where the name matches the profiler marker to measure.</param>
/// <returns>A ProfilerMeasurement instance configured according to the given arguments.</returns>
public static ProfilerMeasurement ProfilerMarkers(params SampleGroup[] sampleGroups)
{
return new ProfilerMeasurement(sampleGroups);
}
/// <summary>
/// Measures execution time for a method with given parameters.
/// </summary>
/// <param name="action">The action to be measured.</param>
/// <returns><see cref="MethodMeasurement"/>using a builder pattern to provide parameters. Call <see cref="ScopeMeasurement.Run"/> to start measurement.</returns>
public static MethodMeasurement Method(Action action)
{
return new MethodMeasurement(action);
}
/// <summary>
/// Measures frame times with given parameters.
/// </summary>
/// <returns><see cref="FramesMeasurement"/> using a builder pattern to provide parameters. Call <see cref="FramesMeasurement.Run"/> method to start measurement.</returns>
public static FramesMeasurement Frames()
{
return new FramesMeasurement();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 788d1fc54ab24f14d80cb45b26012c82
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c0c170ab616b34944bcd5e75cfcb9d06
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,372 @@
using System;
using System.Collections;
using System.Diagnostics;
using Unity.PerformanceTesting.Data;
using Unity.PerformanceTesting.Runtime;
using Unity.PerformanceTesting.Statistics;
using UnityEngine;
using Debug = UnityEngine.Debug;
using Object = UnityEngine.Object;
namespace Unity.PerformanceTesting.Measurements
{
/// <summary>
/// Allows measuring of frame times.
/// </summary>
public class FramesMeasurement
{
private const int k_MinTestTimeMs = 500;
private const int k_MinWarmupTimeMs = 80;
private const int k_ProbingMultiplier = 4;
internal const int k_MinIterations = 7;
internal const int k_MaxDynamicMeasurements = 1000;
private const double k_DefaultMaxRelativeError = 0.02;
private const ConfidenceLevel k_DefaultConfidenceLevel = ConfidenceLevel.L99;
private const OutlierMode k_DefaultOutlierMode = OutlierMode.Remove;
private SampleGroup[] m_ProfilerSampleGroups;
private SampleGroup m_SampleGroup = new SampleGroup("FrameTime");
private int m_DesiredFrameCount;
internal bool m_DynamicMeasurementCount;
private double m_MaxRelativeError = k_DefaultMaxRelativeError;
private ConfidenceLevel m_ConfidenceLevel = k_DefaultConfidenceLevel;
private OutlierMode m_OutlierMode = k_DefaultOutlierMode;
private int m_Executions;
private int m_Warmup = -1;
private bool m_RecordFrametime = true;
/// <summary>
/// Records provided profiler markers once per frame.
/// </summary>
/// <param name="profilerMarkerNames">Profiler marker names as in profiler window.</param>
/// <returns>An updated instance of the FramesMeasurement to be used in fluent syntax.</returns>
public FramesMeasurement ProfilerMarkers(params string[] profilerMarkerNames)
{
m_ProfilerSampleGroups = Utils.CreateSampleGroupsFromMarkerNames(profilerMarkerNames);
return this;
}
/// <summary>
/// Records provided profiler markers once per frame.
/// </summary>
/// <param name="sampleGroups">List of SampleGroups where a name matches the profiler marker and desired SampleUnit</param>
/// <returns>An updated instance of the FramesMeasurement to be used in fluent syntax.</returns>
public FramesMeasurement ProfilerMarkers(params SampleGroup[] sampleGroups)
{
m_ProfilerSampleGroups = sampleGroups;
return this;
}
/// <summary>
/// Overrides the name of default sample group "Time".
/// </summary>
/// <param name="name">Name of the sample group.</param>
/// <returns>An updated instance of the FramesMeasurement to be used in fluent syntax.</returns>
public FramesMeasurement SampleGroup(string name)
{
m_SampleGroup.Name = name;
return this;
}
/// <summary>
/// Overrides the default sample group "Time"
/// </summary>
/// <param name="sampleGroup">Sample group to use.</param>
/// <returns>An updated instance of the FramesMeasurement to be used in fluent syntax.</returns>
public FramesMeasurement SampleGroup(SampleGroup sampleGroup)
{
m_SampleGroup = sampleGroup;
return this;
}
/// <summary>
/// Count of measurements to take.
/// </summary>
/// <param name="count">Count of measurements.</param>
/// <returns>An updated instance of the FramesMeasurement to be used in fluent syntax.</returns>
public FramesMeasurement MeasurementCount(int count)
{
m_Executions = count;
return this;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="outlierMode">Outlier mode allows to include or exclude outliers when evaluating the stop criterion.</param>
/// <returns>An updated instance of the FramesMeasurement to be used in fluent syntax.</returns>
public FramesMeasurement DynamicMeasurementCount(OutlierMode outlierMode = k_DefaultOutlierMode)
{
m_DynamicMeasurementCount = true;
m_OutlierMode = outlierMode;
return this;
}
/// <summary>
/// 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).
/// </summary>
/// <param name="maxRelativeError">The maximum relative error of the mean that the margin of error must fall into.</param>
/// <param name="confidenceLevel">The confidence interval which will be used to calculate the margin of error.</param>
/// <param name="outlierMode">Outlier mode allows to include or exclude outliers when evaluating the stop criterion.</param>
/// <returns>An updated instance of the FramesMeasurement to be used in fluent syntax.</returns>
public FramesMeasurement DynamicMeasurementCount(double maxRelativeError, ConfidenceLevel confidenceLevel = k_DefaultConfidenceLevel,
OutlierMode outlierMode = k_DefaultOutlierMode)
{
m_MaxRelativeError = maxRelativeError;
m_ConfidenceLevel = confidenceLevel;
m_DynamicMeasurementCount = true;
m_OutlierMode = outlierMode;
return this;
}
/// <summary>
/// Count of warmup executions.
/// </summary>
/// <param name="count">Count of warmup executions.</param>
/// <returns>An updated instance of the FramesMeasurement to be used in fluent syntax.</returns>
public FramesMeasurement WarmupCount(int count)
{
m_Warmup = count;
return this;
}
/// <summary>
/// Specifies frame times should not be recorded.
/// </summary>
/// <returns>An updated instance of the FramesMeasurement to be used in fluent syntax.</returns>
public FramesMeasurement DontRecordFrametime()
{
m_RecordFrametime = false;
return this;
}
/// <summary>
/// Switches frame time measurement to asynchronous scope measurement.
/// </summary>
/// <param name="name">Sample group name.</param>
/// <returns>A ScopedFrameTimeMeasurement instance configured according to the given arguments.</returns>
public ScopedFrameTimeMeasurement Scope(string name = "Time")
{
return new ScopedFrameTimeMeasurement(name);
}
/// <summary>
/// Switches frame time measurement to asynchronous scope measurement.
/// </summary>
/// <param name="sampleGroup">Sample group to save measurements.</param>
/// <returns>A ScopedFrameTimeMeasurement instance configured according to the given arguments.</returns>
public ScopedFrameTimeMeasurement Scope(SampleGroup sampleGroup)
{
return new ScopedFrameTimeMeasurement(sampleGroup);
}
/// <summary>
/// Executes the frame time measurement with given parameters. When MeasurementCount is not provided, a probing method will run to determine desired measurement counts.
/// </summary>
/// <returns>IEnumerator to yield until finish.</returns>
public IEnumerator Run()
{
ValidateCorrectDynamicMeasurementCountUsage();
if (!ValidateMeasurementAndWarmupCount()) yield break;
SettingsOverride();
yield return m_Warmup > -1 ? WaitFor(m_Warmup) : GetDesiredIterationCount();
using (Measure.ProfilerMarkers(m_ProfilerSampleGroups))
{
if (m_DynamicMeasurementCount)
{
yield return RunDynamicMeasurementCount();
}
else
{
yield return RunFixedMeasurementCount();
}
// WaitForEndOfFrame coroutine is not invoked on the editor in batch mode
// This may lead to unexpected behavior and is better to avoid
// https://docs.unity3d.com/ScriptReference/WaitForEndOfFrame.html
if (!Application.isBatchMode && Application.isPlaying)
{
yield return new WaitForEndOfFrame();
}
}
}
private IEnumerator RunDynamicMeasurementCount()
{
while (true)
{
using (Measure.Scope(m_SampleGroup))
{
yield return null;
}
if (SampleCountFulfillsRequirements())
break;
}
}
private IEnumerator RunFixedMeasurementCount()
{
m_DesiredFrameCount = m_Executions > 0 ? m_Executions : m_DesiredFrameCount;
for (var i = 0; i < m_DesiredFrameCount; i++)
{
if (m_RecordFrametime)
{
using (Measure.Scope(m_SampleGroup))
{
yield return null;
}
}
else
{
yield return null;
}
}
}
private bool ValidateMeasurementAndWarmupCount()
{
if (m_DynamicMeasurementCount || m_Executions != 0 || m_Warmup < 0) return true;
Debug.LogError("Provide execution count or remove warmup count from frames measurement.");
return false;
}
private void ValidateCorrectDynamicMeasurementCountUsage()
{
if (!m_DynamicMeasurementCount)
return;
if (m_Executions > 0)
{
m_DynamicMeasurementCount = false;
Debug.LogWarning("DynamicMeasurementCount will be ignored because MeasurementCount was specified.");
return;
}
if (!m_RecordFrametime)
{
m_DynamicMeasurementCount = false;
Debug.LogWarning("DynamicMeasurementCount will be ignored because FrameTime measurement was disabled.");
}
}
private bool SampleCountFulfillsRequirements()
{
var samples = m_SampleGroup.Samples;
var sampleCount = samples.Count;
var statistics = MeasurementsStatistics.Calculate(samples, m_OutlierMode, m_ConfidenceLevel);
var actualError = statistics.MarginOfError;
var maxError = m_MaxRelativeError * statistics.Mean;
if (sampleCount >= k_MinIterations && actualError < maxError)
return true;
if (sampleCount >= k_MaxDynamicMeasurements)
return true;
return false;
}
/// <summary>
/// Overrides measurement count based on performance run settings
/// </summary>
private void SettingsOverride()
{
var count = RunSettings.Instance.MeasurementCount;
if (count < 0) { return; }
m_Executions = count;
m_Warmup = m_Warmup < 1 ? 0 : count;
m_DynamicMeasurementCount = false;
}
private IEnumerator GetDesiredIterationCount()
{
var executionTime = 0.0D;
var iterations = 1;
while (executionTime < k_MinWarmupTimeMs)
{
var sw = Stopwatch.GetTimestamp();
yield return WaitFor(iterations);
executionTime = TimeSpan.FromTicks(Stopwatch.GetTimestamp() - sw).TotalMilliseconds;
if (iterations == 1 && executionTime > 40)
{
m_DesiredFrameCount = k_MinIterations;
yield break;
}
if (iterations == 64)
{
m_DesiredFrameCount = 120;
yield break;
}
if (executionTime < k_MinWarmupTimeMs)
{
iterations *= k_ProbingMultiplier;
}
}
m_DesiredFrameCount = (int)(k_MinTestTimeMs * iterations / executionTime);
}
private IEnumerator WaitFor(int iterations)
{
for (var i = 0; i < iterations; i++)
{
yield return null;
}
}
/// <summary>
/// Provides a way to measure frame time within a scope.
/// </summary>
public struct ScopedFrameTimeMeasurement : IDisposable
{
private readonly FrameTimeMeasurement m_Test;
/// <summary>
/// Initializes a scoped frame time measurement.
/// </summary>
/// <param name="sampleGroup">Sample group used to store measurements.</param>
public ScopedFrameTimeMeasurement(SampleGroup sampleGroup)
{
var go = new GameObject("Recorder");
if (Application.isPlaying) Object.DontDestroyOnLoad(go);
m_Test = go.AddComponent<FrameTimeMeasurement>();
m_Test.SampleGroup = sampleGroup;
PerformanceTest.Disposables.Add(this);
}
/// <summary>
/// Initializes a scoped frame time measurement.
/// </summary>
/// <param name="name">Sample group name used to store measurements.</param>
public ScopedFrameTimeMeasurement(string name): this(new SampleGroup(name))
{
}
/// <summary>
/// Stops scoped frame time measurement and adds it to provided sample group.
/// </summary>
public void Dispose()
{
PerformanceTest.Disposables.Remove(this);
Object.DestroyImmediate(m_Test.gameObject);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9f2b7554f46f00c488dabcaaf44ed09e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,14 @@
using UnityEngine;
namespace Unity.PerformanceTesting.Measurements
{
internal class FrameTimeMeasurement : MonoBehaviour
{
public SampleGroup SampleGroup;
void Update()
{
Measure.Custom(SampleGroup, Time.unscaledDeltaTime * 1000);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2ba8bef1806543b47a718ff4d3cb0934
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,516 @@
using System;
using Unity.PerformanceTesting.Data;
using Unity.PerformanceTesting.Exceptions;
using Unity.PerformanceTesting.Meters;
using Unity.PerformanceTesting.Runtime;
using Unity.PerformanceTesting.Statistics;
using Unity.Profiling;
using UnityEngine;
namespace Unity.PerformanceTesting.Measurements
{
/// <summary>
/// Used as a helper class to sample execution time of methods. Uses fluent pattern to build and needs to be executed with Run method.
/// </summary>
public class MethodMeasurement
{
internal const int k_MeasurementCount = 9;
private const int k_MinMeasurementTimeMs = 100;
private const int k_MinWarmupTimeMs = 100;
private const int k_ProbingMultiplier = 4;
private const int k_MaxIterations = 10000;
internal const int k_MaxDynamicMeasurements = 1000;
private const double k_DefaultMaxRelativeError = 0.02;
private const ConfidenceLevel k_DefaultConfidenceLevel = ConfidenceLevel.L99;
private const OutlierMode k_DefaultOutlierMode = OutlierMode.Remove;
private readonly Action m_Action;
private ProfilerMarkerMeasurement m_ProfilerMarkerMeasurement = new ProfilerMarkerMeasurement(averageSampleMeasurement: true);
private ProfilerRecorder m_GCRecorder;
private Action m_Setup;
private Action m_Cleanup;
private SampleGroup m_SampleGroup = new SampleGroup("Time", SampleUnit.Millisecond, false);
private SampleGroup m_SampleGroupGC = new SampleGroup("Time.GC()", SampleUnit.Undefined, false);
private int m_WarmupCount;
private int m_MeasurementCount;
internal bool m_DynamicMeasurementCount;
private double m_MaxRelativeError = k_DefaultMaxRelativeError;
private ConfidenceLevel m_ConfidenceLevel = k_DefaultConfidenceLevel;
private OutlierMode m_OutlierMode = k_DefaultOutlierMode;
private int m_IterationCount = 1;
private bool m_GC;
private IStopWatch m_Watch;
/// <summary>
/// Initializes a method measurement.
/// </summary>
/// <param name="action">Method to be measured.</param>
public MethodMeasurement(Action action)
{
m_Action = action;
if (m_Watch == null) m_Watch = new StopWatch();
}
internal MethodMeasurement StopWatch(IStopWatch watch)
{
m_Watch = watch;
return this;
}
/// <summary>
/// Will record provided profiler markers once per frame.
/// </summary>
/// <param name="profilerMarkerNames">Profiler marker names as in profiler window.</param>
/// <returns>An updated instance of the MethodMeasurement to be used in fluent syntax.</returns>
public MethodMeasurement ProfilerMarkers(params string[] profilerMarkerNames)
{
if (profilerMarkerNames == null)
return this;
foreach (var marker in profilerMarkerNames)
{
var sampleGroup = new SampleGroup(marker, SampleUnit.Nanosecond, false);
m_ProfilerMarkerMeasurement.AddProfilerSample(sampleGroup);
}
return this;
}
/// <summary>
/// Will record provided profiler markers once per frame with additional control over the SampleUnit.
/// </summary>
/// <param name="sampleGroups">List of SampleGroups where a name matches the profiler marker and desired SampleUnit.</param>
/// <returns>An updated instance of the MethodMeasurement to be used in fluent syntax.</returns>
public MethodMeasurement ProfilerMarkers(params SampleGroup[] sampleGroups)
{
if (sampleGroups == null)
return this;
m_ProfilerMarkerMeasurement.AddProfilerSampleGroup(sampleGroups);
return this;
}
/// <summary>
/// Overrides the default SampleGroup of "Time".
/// </summary>
/// <param name="name">Desired name for measurement SampleGroup.</param>
/// <returns>An updated instance of the MethodMeasurement to be used in fluent syntax.</returns>
public MethodMeasurement SampleGroup(string name)
{
m_SampleGroup = new SampleGroup(name, SampleUnit.Millisecond, false);
m_SampleGroupGC = new SampleGroup(name + ".GC()", SampleUnit.Undefined, false);
return this;
}
/// <summary>
/// Overrides the default SampleGroup.
/// </summary>
/// <param name="sampleGroup">SampleGroup with your desired name and unit.</param>
/// <returns>An updated instance of the MethodMeasurement to be used in fluent syntax.</returns>
public MethodMeasurement SampleGroup(SampleGroup sampleGroup)
{
m_SampleGroup = sampleGroup;
m_SampleGroupGC = new SampleGroup(sampleGroup.Name + ".GC()", SampleUnit.Undefined, false);
return this;
}
/// <summary>
/// Count of times to execute before measurements are collected. If unspecified, a default warmup will be assigned.
/// </summary>
/// <param name="count">Count of warmup iterations to execute.</param>
/// <returns>An updated instance of the MethodMeasurement to be used in fluent syntax.</returns>
public MethodMeasurement WarmupCount(int count)
{
m_WarmupCount = count;
return this;
}
/// <summary>
/// Specifies the amount of method executions for a single measurement.
/// </summary>
/// <param name="count">Count of method executions.</param>
/// <returns>An updated instance of the MethodMeasurement to be used in fluent syntax.</returns>
public MethodMeasurement IterationsPerMeasurement(int count)
{
m_IterationCount = count;
return this;
}
/// <summary>
/// Specifies the number of measurements to take.
/// </summary>
/// <param name="count">Count of measurements to take.</param>
/// <returns>An updated instance of the MethodMeasurement to be used in fluent syntax.</returns>
public MethodMeasurement MeasurementCount(int count)
{
m_MeasurementCount = count;
return this;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="outlierMode">Outlier mode allows to include or exclude outliers when evaluating the stop criterion.</param>
/// <returns>An updated instance of the MethodMeasurement to be used in fluent syntax.</returns>
public MethodMeasurement DynamicMeasurementCount(OutlierMode outlierMode = k_DefaultOutlierMode)
{
m_DynamicMeasurementCount = true;
m_OutlierMode = outlierMode;
return this;
}
/// <summary>
/// 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).
/// </summary>
/// <param name="maxRelativeError">The maximum relative error of the mean that the margin of error must fall into.</param>
/// <param name="confidenceLevel">The confidence interval which will be used to calculate the margin of error.</param>
/// <param name="outlierMode">Outlier mode allows to include or exclude outliers when evaluating the stop criterion.</param>
/// <returns>An updated instance of the MethodMeasurement to be used in fluent syntax.</returns>
public MethodMeasurement DynamicMeasurementCount(double maxRelativeError, ConfidenceLevel confidenceLevel = k_DefaultConfidenceLevel,
OutlierMode outlierMode = k_DefaultOutlierMode)
{
m_MaxRelativeError = maxRelativeError;
m_ConfidenceLevel = confidenceLevel;
m_DynamicMeasurementCount = true;
m_OutlierMode = outlierMode;
return this;
}
/// <summary>
/// Used to provide a cleanup method which will not be measured.
/// </summary>
/// <param name="action">Cleanup method to execute.</param>
/// <returns>An updated instance of the MethodMeasurement to be used in fluent syntax.</returns>
public MethodMeasurement CleanUp(Action action)
{
m_Cleanup = action;
return this;
}
/// <summary>
/// Used to provide a setup method which will run before the measurement.
/// </summary>
/// <param name="action">Setup method to execute.</param>
/// <returns>An updated instance of the MethodMeasurement to be used in fluent syntax.</returns>
public MethodMeasurement SetUp(Action action)
{
m_Setup = action;
return this;
}
/// <summary>
/// Enables recording of the number of managed allocations made by the measured method - the "GC.Alloc" counter
/// in the Unity Profiler - as an additional sample group with a ".GC()" name postfix.
/// </summary>
/// <remarks>
/// <para>
/// The recorded value is a count of allocations, not an amount of bytes, and only allocations made on the
/// thread running the measurement are counted. It is reported per iteration when IterationsPerMeasurement is
/// used, and warmup, probing, SetUp and CleanUp are excluded from it.
/// Enabling this also forces 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 the timed region and show
/// up as periodic spikes across the samples. Because of that, the times reported for a method that allocates
/// are not directly comparable between a run with GC() and one without.
/// </para>
/// </remarks>
/// <returns>An updated instance of the MethodMeasurement to be used in fluent syntax.</returns>
public MethodMeasurement GC()
{
if (!m_GC)
{
// Create the GC Alloc recorder
m_GCRecorder = new ProfilerRecorder(ProfilerCategory.Memory, "GC.Alloc", 1,
ProfilerRecorderOptions.WrapAroundWhenCapacityReached | ProfilerRecorderOptions.SumAllSamplesInFrame | ProfilerRecorderOptions.CollectOnlyOnCurrentThread);
Debug.Assert(m_GCRecorder.Valid, "GC.Alloc ProfilerRecorder must be valid for the GC measurements");
m_GC = true;
}
return this;
}
/// <summary>
/// Executes the measurement with given parameters. When MeasurementCount is not provided, a probing method will run to determine desired measurement counts.
/// </summary>
public void Run()
{
ValidateCorrectDynamicMeasurementCountUsage();
SettingsOverride();
var settingsCount = RunSettings.Instance.MeasurementCount;
if (m_MeasurementCount > 0 || settingsCount > -1)
{
// Allocate sample groups up front to minimize GC allocations during/between tests
if (m_GC)
{
m_SampleGroupGC.Samples.Capacity = m_MeasurementCount;
var sampleGroupGC = PerformanceTest.GetSampleGroup(m_SampleGroupGC.Name);
if (sampleGroupGC == null)
{
PerformanceTest.AddSampleGroup(m_SampleGroupGC);
}
}
m_SampleGroup.Samples.Capacity = m_MeasurementCount;
var sampleGroup = PerformanceTest.GetSampleGroup(m_SampleGroup.Name);
if (sampleGroup == null)
{
PerformanceTest.AddSampleGroup(m_SampleGroup);
}
Warmup(m_WarmupCount);
RunForIterations(m_IterationCount, m_MeasurementCount, useAverage: false);
return;
}
if (m_DynamicMeasurementCount)
{
Warmup(m_WarmupCount);
RunForIterations(m_IterationCount);
return;
}
var iterations = Probing();
RunForIterations(iterations, k_MeasurementCount, useAverage: true);
}
private void ValidateCorrectDynamicMeasurementCountUsage()
{
if (!m_DynamicMeasurementCount)
return;
if (m_MeasurementCount > 0)
{
m_DynamicMeasurementCount = false;
Debug.LogWarning("DynamicMeasurementCount will be ignored because MeasurementCount was specified.");
}
}
/// <summary>
/// Overrides measurement count based on performance run settings
/// </summary>
private void SettingsOverride()
{
var count = RunSettings.Instance.MeasurementCount;
if (count < 0) { return; }
m_MeasurementCount = count;
m_WarmupCount = m_WarmupCount > 0 ? count : 0;
m_DynamicMeasurementCount = false;
}
private void RunForIterations(int iterations, int measurements, bool useAverage)
{
// Start marker recorders only for the measured iterations so warmup and probing samples
// do not contribute to the reported marker values
m_ProfilerMarkerMeasurement.StartRecording();
for (var j = 0; j < measurements; j++)
{
var executionTime = iterations == 1 ? ExecuteSingleIteration() : ExecuteForIterations(iterations);
if (useAverage) executionTime /= iterations;
var delta = Utils.ConvertSample(SampleUnit.Millisecond, m_SampleGroup.Unit, executionTime);
Measure.Custom(m_SampleGroup, delta);
}
DisableAndMeasureMarkers();
}
private void RunForIterations(int iterations)
{
// Start marker recorders only for the measured iterations so warmup and probing samples
// do not contribute to the reported marker values
m_ProfilerMarkerMeasurement.StartRecording();
while(true)
{
var executionTime = iterations == 1 ? ExecuteSingleIteration() : ExecuteForIterations(iterations);
var delta = Utils.ConvertSample(SampleUnit.Millisecond, m_SampleGroup.Unit, executionTime);
Measure.Custom(m_SampleGroup, delta);
if (SampleCountFulfillsRequirements())
break;
}
DisableAndMeasureMarkers();
}
private void DisableAndMeasureMarkers()
{
m_ProfilerMarkerMeasurement.SampleProfilerSamples(stopRecorders: true);
m_ProfilerMarkerMeasurement.Dispose();
m_ProfilerMarkerMeasurement = null;
m_GCRecorder.Dispose();
}
private bool SampleCountFulfillsRequirements()
{
var samples = m_SampleGroup.Samples;
var sampleCount = samples.Count;
var statistics = MeasurementsStatistics.Calculate(samples, m_OutlierMode, m_ConfidenceLevel);
var actualError = statistics.MarginOfError;
var maxError = m_MaxRelativeError * statistics.Mean;
if (sampleCount >= k_MeasurementCount && actualError < maxError)
return true;
if (sampleCount >= k_MaxDynamicMeasurements)
return true;
return false;
}
private int Probing()
{
var priorGC = m_GC;
m_GC = false;
var executionTime = 0.0D;
var iterations = 1;
if (m_WarmupCount > 0)
throw new PerformanceTestException(
"Please provide MeasurementCount or remove WarmupCount in your usage of Measure.Method");
while (executionTime < k_MinWarmupTimeMs)
{
executionTime = m_Watch.Split();
Warmup(iterations);
executionTime = m_Watch.Split() - executionTime;
if (executionTime < k_MinWarmupTimeMs)
{
iterations *= k_ProbingMultiplier;
}
}
if (iterations == 1)
{
ExecuteActionWithCleanupSetup();
ExecuteActionWithCleanupSetup();
m_GC = priorGC;
return 1;
}
var deisredIterationsCount =
Mathf.Clamp((int) (k_MinMeasurementTimeMs * iterations / executionTime), 1, k_MaxIterations);
m_GC = priorGC;
return deisredIterationsCount;
}
private void Warmup(int iterations)
{
var priorGC = m_GC;
m_GC = false;
for (var i = 0; i < iterations; i++)
{
ExecuteForIterations(m_IterationCount);
}
m_GC = priorGC;
}
private double ExecuteActionWithCleanupSetup()
{
m_Setup?.Invoke();
if (m_GC)
StartGCRecorder();
var executionTime = m_Watch.Split();
m_Action.Invoke();
executionTime = m_Watch.Split() - executionTime;
if (m_GC)
StopGCRecorder();
m_Cleanup?.Invoke();
return executionTime;
}
private double ExecuteSingleIteration()
{
m_Setup?.Invoke();
if (m_GC)
StartGCRecorder();
var executionTime = m_Watch.Split();
m_Action.Invoke();
executionTime = m_Watch.Split() - executionTime;
if (m_GC)
EndGCRecorderAndMeasure(1);
m_Cleanup?.Invoke();
return executionTime;
}
private double ExecuteForIterations(int iterations)
{
var executionTime = 0.0D;
if (m_Cleanup != null || m_Setup != null)
{
for (var i = 0; i < iterations; i++)
{
executionTime += ExecuteActionWithCleanupSetup();
}
if (m_GC)
EndGCRecorderAndMeasure(iterations);
}
else
{
if (m_GC)
StartGCRecorder();
executionTime = m_Watch.Split();
for (var i = 0; i < iterations; i++)
{
m_Action.Invoke();
}
executionTime = m_Watch.Split() - executionTime;
if (m_GC)
EndGCRecorderAndMeasure(iterations);
}
return executionTime;
}
private void StartGCRecorder()
{
// Collecting here, before the timed region opens, keeps the collection that the measured code's own
// allocations would otherwise trigger from landing inside it. Every caller opens a timed region right
// after this, so with SetUp or CleanUp - where each of the IterationsPerMeasurement inner executions is
// timed separately - this deliberately runs once per inner execution rather than once per sample.
// Fully qualified because this class has its own GC() method.
System.GC.Collect();
m_GCRecorder.Start();
}
private void StopGCRecorder()
{
m_GCRecorder.Stop();
}
private void EndGCRecorderAndMeasure(int iterations)
{
m_GCRecorder.Stop();
var gcAllocCount = m_GCRecorder.Count > 0 ? m_GCRecorder.GetSample(0).Count : 0;
Measure.Custom(m_SampleGroupGC, gcAllocCount / iterations);
m_GCRecorder.Reset();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 573489ea329e0b246a993a3c9bcd9b5c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using Unity.PerformanceTesting.Runtime;
using Unity.Profiling;
using UnityEngine;
namespace Unity.PerformanceTesting.Measurements
{
class ProfilerMarkerMeasurement : IDisposable
{
private readonly bool m_AverageSampleMeasurement;
bool m_DisposedValue;
bool m_RecordingStarted;
protected struct RecordedSampleGroup
{
public SampleGroup SampleGroup;
public ProfilerRecorder ProfilerRecorder;
}
protected readonly List<RecordedSampleGroup> m_SampleGroups = new List<RecordedSampleGroup>();
public ProfilerMarkerMeasurement(bool averageSampleMeasurement)
{
m_AverageSampleMeasurement = averageSampleMeasurement;
}
public void AddProfilerSampleGroup(IEnumerable<SampleGroup> sampleGroups)
{
foreach (var sampleGroup in sampleGroups)
{
AddProfilerSample(sampleGroup);
}
}
public void AddProfilerSample(SampleGroup sampleGroup)
{
m_SampleGroups.Add(new RecordedSampleGroup { SampleGroup = sampleGroup });
}
/// <summary>
/// Creates and starts the recorders for all registered sample groups. Samples produced by the
/// measured markers before this call are not part of the measurement, which allows warmup
/// iterations to be excluded from the reported values.
/// </summary>
public void StartRecording()
{
if (m_RecordingStarted)
return;
m_RecordingStarted = true;
for (var i = 0; i < m_SampleGroups.Count; i++)
{
var sampleGroup = m_SampleGroups[i];
sampleGroup.ProfilerRecorder = new ProfilerRecorder(sampleGroup.SampleGroup.Name, 1,
ProfilerRecorderOptions.WrapAroundWhenCapacityReached | ProfilerRecorderOptions.SumAllSamplesInFrame | ProfilerRecorderOptions.StartImmediately);
m_SampleGroups[i] = sampleGroup;
}
}
public void SampleProfilerSamples(bool stopRecorders = false)
{
foreach (var sampleGroup in m_SampleGroups)
{
// Validate that the recorder is attached to a valid marker. This check must stay ahead of
// any Stop/GetSample call: it also skips recorders that were never started (default handle),
// on which Stop would throw InvalidOperationException
if (!sampleGroup.ProfilerRecorder.Valid)
{
Debug.LogError($"ProfilerMarker measurement is attached to invalid marker \"{sampleGroup.SampleGroup.Name}\"! Ensure the marker is created at the time of the measurement");
continue;
}
if (stopRecorders)
sampleGroup.ProfilerRecorder.Stop();
var delta = 0.0;
// Record the last recorded value if present, otherwise use 0.
if (sampleGroup.ProfilerRecorder.Count > 0 && sampleGroup.ProfilerRecorder.GetSample(0).Count > 0)
{
var sampleCount = m_AverageSampleMeasurement ? sampleGroup.ProfilerRecorder.GetSample(0).Count : 1;
if (sampleCount > 0)
{
var totalTimeNs = sampleGroup.ProfilerRecorder.GetSample(0).Value / sampleCount;
delta = Utils.ConvertSample(SampleUnit.Nanosecond, sampleGroup.SampleGroup.Unit, totalTimeNs);
}
}
Measure.Custom(sampleGroup.SampleGroup, delta);
}
}
public void StopAndSampleRecorders() => SampleProfilerSamples(true);
protected virtual void Dispose(bool disposing)
{
if (m_DisposedValue)
return;
foreach (var sampleGroup in m_SampleGroups)
{
sampleGroup.ProfilerRecorder.Dispose();
}
m_DisposedValue = true;
}
~ProfilerMarkerMeasurement()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: false);
}
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: aa2734fdf41ccae4d8e95492e9e75620
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,60 @@
using System;
using Unity.PerformanceTesting.Runtime;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Unity.PerformanceTesting.Measurements
{
/// <summary>
/// Provides a way to measure profiler markers.
/// </summary>
public struct ProfilerMeasurement : IDisposable
{
private readonly ProfilerMeasurementBehaviour m_Test;
/// <summary>
/// Initializes a profiler marker measurement.
/// </summary>
/// <param name="sampleGroups">List of sample groups with name set to match profiler markers to be measured.</param>
public ProfilerMeasurement(SampleGroup[] sampleGroups)
{
if (sampleGroups == null)
{
m_Test = null;
return;
}
if (sampleGroups.Length == 0)
{
m_Test = null;
return;
}
var go = new GameObject("Recorder");
if (Application.isPlaying) Object.DontDestroyOnLoad(go);
go.hideFlags = HideFlags.HideAndDontSave;
m_Test = go.AddComponent<ProfilerMeasurementBehaviour>();
m_Test.AddProfilerSampleGroup(sampleGroups);
PerformanceTest.Disposables.Add(this);
}
/// <summary>
/// Initializes a profiler marker measurement.
/// </summary>
/// <param name="profilerMarkers">List of profiler markers to be measured.</param>
public ProfilerMeasurement(string[] profilerMarkers): this(Utils.CreateSampleGroupsFromMarkerNames(profilerMarkers))
{
}
/// <summary>
/// Stops profiler marker measurement and adds them to the provided sample group.
/// </summary>
public void Dispose()
{
PerformanceTest.Disposables.Remove(this);
if (m_Test == null) return;
m_Test.StopAndSampleRecorders();
Object.DestroyImmediate(m_Test.gameObject);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 848e89034d174c77aae5f9f6a46b904b
timeCreated: 1617691772
@@ -0,0 +1,44 @@
using System.Collections.Generic;
using Unity.PerformanceTesting.Runtime;
using Unity.Profiling;
using UnityEngine;
namespace Unity.PerformanceTesting.Measurements
{
class ProfilerMeasurementBehaviour : MonoBehaviour
{
private bool m_MeasurementStarted = false;
private ProfilerMarkerMeasurement m_ProfilerMarkerMeasurement = new ProfilerMarkerMeasurement(averageSampleMeasurement: false);
public void AddProfilerSampleGroup(IEnumerable<SampleGroup> sampleGroups)
{
m_ProfilerMarkerMeasurement.AddProfilerSampleGroup(sampleGroups);
// Frame measurements sample once per frame, so recording starts right away
m_ProfilerMarkerMeasurement.StartRecording();
}
public void StopAndSampleRecorders()
{
m_ProfilerMarkerMeasurement.StopAndSampleRecorders();
}
public void Update()
{
// Skip one frame where we just start recording and don't have full data yet
if (!m_MeasurementStarted)
{
m_MeasurementStarted = true;
}
else
{
m_ProfilerMarkerMeasurement.SampleProfilerSamples();
}
}
public void OnDestroy()
{
m_ProfilerMarkerMeasurement.Dispose();
m_ProfilerMarkerMeasurement = null;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e55bf1c69e5bb204d848e5a8ff5da346
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,54 @@
using System;
using System.Diagnostics;
using Unity.PerformanceTesting.Runtime;
namespace Unity.PerformanceTesting.Measurements
{
/// <summary>
/// Measures execution time for the given scope as a single time.
/// </summary>
public struct ScopeMeasurement : IDisposable
{
private readonly SampleGroup m_SampleGroup;
private readonly long m_StartTicks;
/// <summary>
/// Initializes a scope measurement.
/// </summary>
/// <param name="sampleGroup">Sample group used to save measurements.</param>
public ScopeMeasurement(SampleGroup sampleGroup)
{
m_SampleGroup = PerformanceTest.GetSampleGroup(sampleGroup.Name);
if (m_SampleGroup == null)
{
m_SampleGroup = sampleGroup;
PerformanceTest.Active.SampleGroups.Add(m_SampleGroup);
}
m_StartTicks = Stopwatch.GetTimestamp();
PerformanceTest.Disposables.Add(this);
}
/// <summary>
/// Initializes a scope measurement.
/// </summary>
/// <param name="name">Sample group name used for measurements.</param>
public ScopeMeasurement(string name) : this(new SampleGroup(name))
{
}
/// <summary>
/// Stops scope measurement and adds it to provided sample group.
/// </summary>
public void Dispose()
{
var elapsedTicks = Stopwatch.GetTimestamp() - m_StartTicks;
PerformanceTest.Disposables.Remove(this);
var delta = TimeSpan.FromTicks(elapsedTicks).TotalMilliseconds;
delta = Utils.ConvertSample(SampleUnit.Millisecond, m_SampleGroup.Unit, delta);
Measure.Custom(m_SampleGroup, delta);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f7250ae0d09b4f228bb132e8f30d3f6e
timeCreated: 1617691887
@@ -0,0 +1,111 @@
using System;
using System.Globalization;
using Unity.PerformanceTesting.Data;
using Unity.PerformanceTesting.Runtime;
using UnityEngine;
#if USE_CUSTOM_METADATA
using com.unity.test.metadatamanager;
#endif
namespace Unity.PerformanceTesting
{
/// <summary>
/// Helper class to retrieve metadata information about player settings and hardware.
/// </summary>
public static class Metadata
{
/// <summary>
/// Gets hardware information.
/// </summary>
/// <returns>Hardware information.</returns>
public static Hardware GetHardware()
{
return new Hardware
{
OperatingSystem = SystemInfo.operatingSystem,
DeviceModel = SystemInfo.deviceModel,
DeviceName = SystemInfo.deviceName,
ProcessorType = SystemInfo.processorType,
ProcessorCount = SystemInfo.processorCount,
GraphicsDeviceName = SystemInfo.graphicsDeviceName,
SystemMemorySizeMB = SystemInfo.systemMemorySize
};
}
/// <summary>
/// Sets player settings.
/// </summary>
/// <param name="run">Run used to set settings.</param>
public static void SetPlayerSettings(Run run)
{
run.Player.Vsync = QualitySettings.vSyncCount;
run.Player.AntiAliasing = QualitySettings.antiAliasing;
run.Player.ColorSpace = QualitySettings.activeColorSpace.ToString();
run.Player.AnisotropicFiltering = QualitySettings.anisotropicFiltering.ToString();
run.Player.BlendWeights = QualitySettings.skinWeights.ToString();
#if UNITY_2022_2_OR_NEWER
run.Player.ScreenRefreshRate = (int)Math.Round(Screen.currentResolution.refreshRateRatio.value); // casting to int and rounding to ensure backwards compatibility with older package versions
#else
run.Player.ScreenRefreshRate = Screen.currentResolution.refreshRate;
#endif
run.Player.ScreenWidth = Screen.currentResolution.width;
run.Player.ScreenHeight = Screen.currentResolution.height;
run.Player.Fullscreen = Screen.fullScreen;
run.Player.Batchmode = Application.isBatchMode;
run.Player.Development = Application.isEditor || Debug.isDebugBuild;
run.Player.Platform = Application.platform.ToString();
run.Player.GraphicsApi = SystemInfo.graphicsDeviceType.ToString();
run.Player.RenderThreadingMode = SystemInfo.renderingThreadingMode.ToString();
run.Player.MtRendering = SystemInfo.graphicsMultiThreaded;
run.Player.GraphicsJobs = SystemInfo.renderingThreadingMode.ToString().IndexOf("Job", StringComparison.InvariantCultureIgnoreCase) >= 0;
// This is a bit of a hack, but there isn't currently a way to get this information at runtime. Eventually this will be a proper player setting we can query.
try
{
run.Player.UnityGraphicsKernel = Array.Exists(Environment.GetCommandLineArgs(), arg => arg.Equals("-force-ugk", StringComparison.OrdinalIgnoreCase));
}
catch (NotSupportedException)
{
// In some environments (WebGL) we can't query command line arguments, so we just catch the exception and move on, leaving this field with its default value of false.
// When UGK supports these platforms we can update this code to properly query the player setting instead of relying on command line arguments.
}
}
/// <summary>
/// Loads run from resources.
/// </summary>
/// <returns>Performance run data loaded from resources.</returns>
public static Run GetFromResources()
{
var run = ResourcesLoader.Load<Run>(Utils.TestRunInfo, Utils.PlayerPrefKeyRunJSON);
SetRuntimeSettings(run);
return run;
}
/// <summary>
/// Sets runtime player settings on a run.
/// </summary>
/// <param name="run">Run used to set settings.</param>
public static void SetRuntimeSettings(Run run)
{
run.Hardware = GetHardware();
SetPlayerSettings(run);
run.TestSuite = Application.isPlaying ? "Playmode" : "Editmode";
#if USE_CUSTOM_METADATA
SetCustomMetadata(run);
#endif
}
#if USE_CUSTOM_METADATA
private static void SetCustomMetadata(Run run)
{
var customMetadataManager = new CustomMetadataManager(run.Dependencies);
// This field is historically not used so we can safely store additional string delimited
// metadata here, then parse the metadata values out on the SQL side to give us access
// to additional metadata that would normally require a schema change, or a property back field
run.Player.AndroidTargetSdkVersion = customMetadataManager.GetCustomMetadata();
}
#endif
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 9cbc3126881d4a31b7b5745739712523
timeCreated: 1604485107
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 29eafdd9eaae4d7995048ee61cd0b7d2
timeCreated: 1614770904
@@ -0,0 +1,19 @@
namespace Unity.PerformanceTesting.Meters
{
/// <summary>
/// Provides stopwatch functionality for measuring time
/// </summary>
internal interface IStopWatch
{
/// <summary>
/// Resets and starts the stopwatch
/// </summary>
void Start();
/// <summary>
/// Takes a split time since start of stopwatch
/// </summary>
/// <returns>Time passed since start in milliseconds</returns>
double Split();
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c9c6fc292cac43d7a2bc05803fd5f49f
timeCreated: 1614770905
@@ -0,0 +1,22 @@
using System.Diagnostics;
namespace Unity.PerformanceTesting.Meters
{
/// <summary>
/// Takes use of System.Diagnostics.Stopwatch to provide stopwatch functionality implementing IStopWatch
/// </summary>
internal class StopWatch : IStopWatch
{
private readonly Stopwatch m_StopWatch = Stopwatch.StartNew();
public void Start()
{
m_StopWatch.Restart();
}
public double Split()
{
return m_StopWatch.Elapsed.TotalMilliseconds;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: daadf59f728a42a795a0ce3559352f4d
timeCreated: 1614771565
@@ -0,0 +1,344 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using Unity.PerformanceTesting.Runtime;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using Unity.PerformanceTesting.Exceptions;
using UnityEngine;
using UnityEngine.TestRunner.NUnitExtensions;
[assembly: InternalsVisibleTo("Unity.PerformanceTesting.Tests.Editor")]
namespace Unity.PerformanceTesting
{
/// <summary>
/// Represents active performance test as a singleton.
/// </summary>
[Serializable]
public class PerformanceTest
{
/// <summary>
/// Full name of the test.
/// </summary>
public string Name;
/// <summary>
/// Class name of the test.
/// </summary>
public string ClassName;
/// <summary>
/// Method name of the test.
/// </summary>
public string MethodName;
/// <summary>
/// Version of the test. Default "1".
/// </summary>
public string Version;
/// <summary>
/// List of categories assigned to the test.
/// </summary>
public List<string> Categories = new List<string>();
/// <summary>
/// List of sample groups assigned to the test.
/// </summary>
public List<SampleGroup> SampleGroups = new List<SampleGroup>();
/// <summary>
/// A default threshold value intended to indicate no performance regression threshold is active for a given performance test.
/// </summary>
internal const double DefaultThresholdValue = -1.0;
/// <summary>
/// List of sample groups assigned to the test.
/// </summary>
internal const double ThresholdSerializationCutOff = 0.0;
/// <summary>
/// Performance regression threshold to be used by a performance test reporting service
/// </summary>
[NonSerialized]
public double Threshold = DefaultThresholdValue;
/// <summary>
/// Singleton instance of active performance test.
/// </summary>
public static PerformanceTest Active { get; set; }
private static List <IDisposable> m_Disposables = new List<IDisposable>(1024);
internal static List<IDisposable> Disposables
{
get => m_Disposables;
set => m_Disposables = value ?? new List<IDisposable>(1024);
}
PerformanceTestHelper m_PerformanceTestHelper;
/// <summary>
/// An action to be invoked when a performance test has finished execution.
/// </summary>
public static event Action OnTestEnded;
/// <summary>
/// Initializes a new performance test and assigns it as singleton.
/// </summary>
public PerformanceTest()
{
Active = this;
}
internal static void StartTest(ITest currentTest)
{
if (currentTest.IsSuite) return;
var go = new GameObject("PerformanceTestHelper");
go.hideFlags = HideFlags.HideAndDontSave;
var performanceTestHelper = go.AddComponent<PerformanceTestHelper>();
string methodName = currentTest.Name.Contains("(")
? currentTest.Name.Remove(currentTest.Name.IndexOf("(", StringComparison.Ordinal))
: currentTest.Name;
string className = currentTest.ClassName;
var fullName = currentTest.MethodName != methodName ? $"{currentTest.ClassName}.{currentTest.MethodName}.{currentTest.Name}" : currentTest.FullName;
var test = new PerformanceTest
{
Name = fullName,
ClassName = className,
MethodName = methodName,
Categories = currentTest.GetAllCategoriesFromTest(),
Version = GetVersion(currentTest),
Threshold = GetThreshold(currentTest),
m_PerformanceTestHelper = performanceTestHelper
};
Active = test;
performanceTestHelper.ActiveTest = test;
}
private static double GetThreshold(ITest currentTest)
{
var thresholdProperty = currentTest.Properties.Get("Threshold");
if (thresholdProperty != null)
return Convert.ToDouble(thresholdProperty);
return DefaultThresholdValue;
}
private static string GetVersion(ITest currentTest)
{
string version = "";
var methodVersions = currentTest.Method.GetCustomAttributes<VersionAttribute>(false);
var classVersion = currentTest.TypeInfo.Type.GetCustomAttributes(typeof(VersionAttribute), true);
if (classVersion.Length > 0)
version = ((VersionAttribute)classVersion[0]).Version + ".";
if (methodVersions.Length > 0)
version += methodVersions[0].Version;
else
version += "1";
return version;
}
internal static void EndTest(ITest test)
{
if (test.IsSuite) return;
if (Active.m_PerformanceTestHelper != null && Active.m_PerformanceTestHelper.gameObject != null)
{
UnityEngine.Object.DestroyImmediate(Active.m_PerformanceTestHelper.gameObject);
}
try
{
DisposeMeasurements();
Active.CalculateStatisticalValues();
try
{
// Notify subscribers that the test has ended by invoking OnTestEnded event
OnTestEnded?.Invoke();
}
catch (Exception ex)
{
// An exception occurred while invoking the OnTestEnded event.
// Log the error message, exception type, and stack trace for troubleshooting.
Debug.LogError($"An exception occurred in OnTestEnd callback: {ex.GetType()}: {ex.Message}\n{ex.StackTrace}");
}
// Must stay inside the try: logging while an earlier exception unwinds would throw again on
// the same sample groups and replace it, hiding the original failure.
LogResults();
}
finally
{
// Runs on every path, including a failure above. Leaving Active set would make
// PerformanceAttribute.BeforeTest skip StartTest for the next test, so a single failing test
// would otherwise take down every performance test that runs after it.
Active = null; // Clear active object
GC.Collect(); // Trigger garbage collection to free resources
}
}
internal static void LogResults()
{
Active.LogOutput(); // Log test output
TestContext.Out.WriteLine("##performancetestresult2:" + Active.Serialize()); // Log test result
PlayerCallbacks.LogMetadata(); // Log metadata
}
private static void DisposeMeasurements()
{
for (var i = 0; i < Disposables.Count; i++)
{
Disposables[i].Dispose();
}
Disposables.Clear();
}
/// <summary>
/// Retrieves named sample group from active performance test.
/// </summary>
/// <param name="name">Name of sample group to retrieve.</param>
/// <returns>Selected sample group.</returns>
/// <exception cref="PerformanceTestException">Exception will be thrown if there is no active performance test.</exception>
public static SampleGroup GetSampleGroup(string name)
{
if (Active == null) throw new PerformanceTestException("Trying to record samples but there is no active performance tests.");
foreach (var sampleGroup in Active.SampleGroups)
{
if (sampleGroup.Name == name)
return sampleGroup;
}
return null;
}
/// <summary>
/// Adds sample group to active performance test.
/// </summary>
/// <param name="sampleGroup">Sample group to be added.</param>
public static void AddSampleGroup(SampleGroup sampleGroup)
{
Active.SampleGroups.Add(sampleGroup);
}
internal string Serialize()
{
var output = JsonUtility.ToJson(this);
if (Threshold > ThresholdSerializationCutOff)
{
// JsonUtility.ToJson always emits a flat "{...}" with no trailing whitespace,
// and PerformanceTest always has other fields, so we can safely splice the
// Threshold key in just before the closing brace. Threshold is [NonSerialized]
// so JsonUtility itself will never include it.
var threshold = Threshold.ToString("R", System.Globalization.CultureInfo.InvariantCulture);
output = output.Substring(0, output.Length - 1) + ",\"Threshold\":" + threshold + "}";
}
return output;
}
/// <summary>
/// Loops through sample groups and updates statistical values.
/// </summary>
public void CalculateStatisticalValues()
{
foreach (var sampleGroup in SampleGroups)
{
sampleGroup.UpdateStatistics();
}
}
private void LogOutput()
{
TestContext.Out.WriteLine(ToString());
}
static void AppendVisualization(StringBuilder sb, IList<double> data, int n, double min, double max)
{
const string bars = "▁▂▃▄▅▆▇█";
double range = max - min;
for (int i = 0; i < n; i++)
{
var sample = data[i];
int idx = Mathf.Clamp(Mathf.RoundToInt((float) ((sample - min) / range * (bars.Length - 1))), 0, bars.Length - 1);
sb.Append(bars[idx]);
}
}
private static double[] s_Buckets;
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod]
static void ResetStaticsOnLoad()
{
m_Disposables?.Clear();
OnTestEnded = null;
s_Buckets = null;
}
#endif
static void AppendSampleHistogram(StringBuilder sb, SampleGroup s, int buckets)
{
if (s_Buckets == null || s_Buckets.Length < buckets)
s_Buckets = new double[buckets];
double maxInOneBucket = 0;
double min = s.Min;
double bucketsOverRange = (buckets - 1) / (s.Max - s.Min);
for (int i = 0; i < s.Samples.Count; i++)
{
int bucket = Mathf.Clamp(Mathf.RoundToInt((float)((s.Samples[i] - min) * bucketsOverRange)), 0, buckets - 1);
s_Buckets[bucket] += 1;
if (s_Buckets[bucket] > maxInOneBucket)
maxInOneBucket = s_Buckets[bucket];
}
AppendVisualization(sb, s_Buckets, s_Buckets.Length, 0, maxInOneBucket);
}
/// <summary>
/// Returns performance test in a readable format.
/// </summary>
/// <returns>Readable representation of performance test.</returns>
public override string ToString()
{
var logString = new StringBuilder();
foreach (var s in SampleGroups)
{
logString.Append(s.Name);
if (s.Samples.Count == 1)
{
logString.AppendLine($" {s.Samples[0]:0.00} {s.Unit}s");
}
else
{
string u = s.Unit.ShortName();
logString.AppendLine($" in {s.Unit}s\nMin:\t\t{s.Min:0.00} {u}\nMedian:\t\t{s.Median:0.00} {u}\nMax:\t\t{s.Max:0.00} {u}\nAvg:\t\t{s.Average:0.00} {u}\nStdDev:\t\t{s.StandardDeviation:0.00} {u}\nSampleCount:\t{s.Samples.Count}\nSum:\t\t{s.Sum:0.00} {u}");
logString.Append("First samples:\t");
AppendVisualization(logString, s.Samples, Mathf.Min(s.Samples.Count, 100), s.Min, s.Max);
logString.AppendLine();
if (s.Samples.Count <= 512)
{
int numBuckets = Mathf.Min(10, s.Samples.Count / 4);
if (numBuckets > 2)
{
logString.Append("Histogram:\t");
AppendSampleHistogram(logString, s, numBuckets);
logString.AppendLine();
}
else
logString.Append("(not enough samples for histogram)\n");
}
logString.AppendLine();
}
}
return logString.ToString();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 357714a00c191294d87f51252d5f7d92
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,18 @@
using System;
namespace Unity.PerformanceTesting.Exceptions
{
/// <summary>
/// Performance test exception.
/// </summary>
[Serializable]
public class PerformanceTestException : System.Exception
{
/// <summary>
/// Performance test exception. Used to indicate failures while running a performance test.
/// </summary>
/// <param name="message">Exception message.</param>
public PerformanceTestException(string message)
: base(message) { }
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 45422469be932c24aa3fc0ed68b1c6d9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,10 @@
using UnityEngine;
namespace Unity.PerformanceTesting
{
internal class PerformanceTestHelper : MonoBehaviour
{
[SerializeField]
public PerformanceTest ActiveTest;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d1ed5968494d4f81bd53a7c212ca8d72
timeCreated: 1608729439
@@ -0,0 +1,65 @@
using UnityEngine.TestRunner;
using Unity.PerformanceTesting;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using Unity.PerformanceTesting.Data;
using Unity.PerformanceTesting.Runtime;
using UnityEngine.Scripting;
using UnityEngine;
[assembly: TestRunCallback(typeof(PlayerCallbacks))]
namespace Unity.PerformanceTesting
{
[Preserve]
internal class PlayerCallbacks : ITestRunCallback
{
internal static bool Saved { get; set; }
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void ResetStaticsOnLoad()
{
Saved = false;
}
#endif
public void RunStarted(ITest testsToRun)
{
// This method is empty because it's part of the NUnit framework's ITestListener interface,
// which Unity uses for running tests in the Editor. It receives a parameter "testsToRun" but
// doesn't require implementation as Unity can execute tests without it. Developers can add
// custom initialization logic if needed.
}
public void RunFinished(ITestResult testResults)
{
Saved = false;
}
public void TestStarted(ITest test)
{
// This method is called by Unity when a new test has started. It receives a parameter "test"
// which contains information about the test being executed. Developers can add custom logic
// in this method, such as logging or setup code for the test.
}
public void TestFinished(ITestResult result)
{
// This method is called by Unity when a test has finished executing. It receives a parameter
// "result" which contains information about the test execution, such as whether the test
// passed or failed, and any messages or exceptions thrown during the test. Developers can
// add custom logic in this method, such as logging or teardown code for the test.
}
internal static void LogMetadata()
{
if (Saved) return;
var run = Metadata.GetFromResources();
var json = JsonUtility.ToJson(run);
TestContext.Out?.WriteLine("##performancetestruninfo2:" + json);
Saved = true;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: adeb1350b6faa3f49b2e8eeca35edc53
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,25 @@
using System;
using UnityEngine;
namespace Unity.PerformanceTesting
{
internal static class ResourcesLoader
{
public static T Load<T>(string assetPath, string prefsKey) where T : class
{
try
{
var runResource = Resources.Load<TextAsset>(assetPath.Replace(".json", ""));
var json = Application.isEditor ? PlayerPrefs.GetString(prefsKey) : runResource.text;
var run = JsonUtility.FromJson<T>(json);
return run;
}
catch (Exception e)
{
Debug.LogError(e);
}
return null;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 9f7fc0eedf514939aced1b50b9163974
timeCreated: 1617795545
@@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Unity.PerformanceTesting.Exceptions;
using UnityEngine.Profiling;
namespace Unity.PerformanceTesting
{
/// <summary>
/// Represents a performance test sample group.
/// </summary>
[Serializable]
public class SampleGroup : IDeserializationCallback
{
/// <summary>
/// Name of the sample group.
/// </summary>
public string Name;
/// <summary>
/// Measurement unit.
/// </summary>
public SampleUnit Unit;
/// <summary>
/// Whether the measurement is inverted and increase is positive.
/// </summary>
public bool IncreaseIsBetter;
/// <summary>
/// List of samples.
/// </summary>
public List<double> Samples = new List<double>();
/// <summary>
/// Minimum value of samples.
/// </summary>
public double Min;
/// <summary>
/// Maximum value of samples.
/// </summary>
public double Max;
/// <summary>
/// Medina value of samples.
/// </summary>
public double Median;
/// <summary>
/// Average value of samples.
/// </summary>
public double Average;
/// <summary>
/// Standard deviation of samples.
/// </summary>
public double StandardDeviation;
/// <summary>
/// Sum of samples.
/// </summary>
public double Sum;
/// <summary>
/// Creates a new sample group with given parameters.
/// </summary>
/// <param name="name">Name of the sample group.</param>
/// <param name="unit">Unit of measurement.</param>
/// <param name="increaseIsBetter">Whether the measurement is inverted and increase is positive.</param>
/// <exception cref="PerformanceTestException">Exception can be thrown if empty or null name is provided.</exception>
public SampleGroup(string name, SampleUnit unit = SampleUnit.Millisecond, bool increaseIsBetter = false)
{
Name = name;
Unit = unit;
IncreaseIsBetter = increaseIsBetter;
if (string.IsNullOrEmpty(name))
{
throw new PerformanceTestException("Sample group name is empty. Please assign a valid name.");
}
}
internal Recorder Recorder;
/// <summary>
/// Gets the profiler recorder object.
/// </summary>
/// <returns>Profiler recorder.</returns>
/// <remarks>This method is obsolete and will be removed in a future version. The recorder is automatically created by <see cref="Unity.PerformanceTesting.Measurements.MethodMeasurement"/> when needed.</remarks>
[Obsolete("GetRecorder is obsolete and will be removed in a future version. The recorder is automatically created by MethodMeasurement when needed.")]
public Recorder GetRecorder()
{
return Recorder ?? (Recorder = Recorder.Get(Name));
}
/// <summary>
/// Validates the deserialized object.
/// </summary>
/// <param name="sender">The object that initiated the deserialization process.</param>
public void OnDeserialization(object sender)
{
if (string.IsNullOrEmpty(Name))
{
throw new PerformanceTestException("Sample group name is empty. Please assign a valid name.");
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 73f2494dd08c9be49b00d97aada5ee77
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 18966f2a7fc5d4073a425a1a3d564494
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,30 @@
using System;
namespace Unity.PerformanceTesting.Statistics
{
/// <summary>
/// Represents a statistical confidence level.
/// </summary>
public enum ConfidenceLevel
{
/// <summary>
/// 90.0% confidence interval
/// </summary>
L90,
/// <summary>
/// 95.0% confidence interval
/// </summary>
L95,
/// <summary>
/// 99.0% confidence interval
/// </summary>
L99,
/// <summary>
/// 99.9% confidence interval
/// </summary>
L999
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 00438930dbe34b76b23c0046d05948b1
timeCreated: 1634592760
@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Unity.PerformanceTesting.Statistics
{
static class ConfidenceLevelExtensions
{
private static readonly Dictionary<ConfidenceLevel, (int value, int digits)> k_ConfidenceLevelDetails = CreateConfidenceLevelMapping();
/// <summary>
/// Calculates Z value (z-star) for confidence interval
/// </summary>
/// <param name="level">ConfidenceLevel for a confidence interval</param>
/// <param name="n">Sample size (n >= 3)</param>
public static double GetZValue(this ConfidenceLevel level, int n)
{
if (n <= 1)
throw new ArgumentOutOfRangeException(nameof(n), "n should be >= 2");
return StudentDistributionHelper.InverseTwoTailedStudent(1 - level.ToPercent(), n - 1);
}
static double ToPercent(this ConfidenceLevel level)
{
(int value, int digits) = k_ConfidenceLevelDetails[level];
return value / Math.Pow(10, digits);
}
static Dictionary<ConfidenceLevel, (int value, int length)> CreateConfidenceLevelMapping()
{
return Enum.GetValues(typeof(ConfidenceLevel))
.Cast<ConfidenceLevel>()
.ToDictionary(
confidenceLevel => confidenceLevel,
confidenceLevel =>
{
var textRepresentation = confidenceLevel.ToString().Substring(1);
return (int.Parse(textRepresentation), textRepresentation.Length);
});
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 88e4f63cb3be45a6afbc8f43bc4683d1
timeCreated: 1634592713
@@ -0,0 +1,170 @@
using System;
using System.Collections.Generic;
namespace Unity.PerformanceTesting.Statistics
{
/// <summary>
/// Provides basic measurement statistics calculated for a sample collection.
/// </summary>
readonly ref struct MeasurementsStatistics
{
/// <summary>
/// Mean of the samples.
/// </summary>
public double Mean { get; }
/// <summary>
/// Margin of error within the requested confidence interval.
/// </summary>
public double MarginOfError { get; }
MeasurementsStatistics(double mean, double marginOfError)
{
Mean = mean;
MarginOfError = marginOfError;
}
/// <summary>
/// Calculates basic measurement statistics for a sample collection.
/// </summary>
/// <param name="measurements">The sample collection.</param>
/// <param name="outlierMode">Outlier removal mode.</param>
/// <param name="confidenceLevel">Confidence interval for calculating the margin of error.</param>
/// <returns>A MeasurementStatistics instance calculated for the provided data.</returns>
/// <exception cref="InvalidOperationException">Thrown if the sample count is zero.</exception>
public static MeasurementsStatistics Calculate(List<double> measurements, OutlierMode outlierMode, ConfidenceLevel confidenceLevel)
{
var n = measurements.Count;
if (n == 0)
throw new InvalidOperationException("Requesting statistic measurements of a sequence which contains no elements.");
double sum;
double mean;
double variance;
double standardDeviation;
double standardError;
double marginOfError;
if (outlierMode == OutlierMode.DontRemove)
{
sum = Sum(measurements);
mean = sum / n;
variance = Variance(measurements, n, mean);
standardDeviation = Math.Sqrt(variance);
standardError = standardDeviation / Math.Sqrt(n);
marginOfError = n <= 2 ? double.NaN : standardError * confidenceLevel.GetZValue(n);
return new MeasurementsStatistics(mean, marginOfError);
}
measurements.Sort();
double q1, q3;
if (n == 1)
q1 = q3 = measurements[0];
else
{
q1 = GetQuartile(measurements, measurements.Count / 2);
q3 = GetQuartile(measurements, measurements.Count * 3 / 2);
}
var interquartileRange = q3 - q1;
var lowerFence = q1 - 1.5 * interquartileRange;
var upperFence = q3 + 1.5 * interquartileRange;
SumWithoutOutliers(outlierMode, measurements, lowerFence, upperFence, out sum, out n);
mean = sum / n;
variance = VarianceWithoutOutliers(outlierMode, measurements, n, mean, lowerFence, upperFence);
standardDeviation = Math.Sqrt(variance);
standardError = standardDeviation / Math.Sqrt(n);
marginOfError = n <= 2 ? double.NaN : standardError * confidenceLevel.GetZValue(n);
return new MeasurementsStatistics(mean, marginOfError);
}
static double Sum(List<double> measurements)
{
var sum = 0d;
foreach (var m in measurements)
{
sum += m;
}
return sum;
}
static void SumWithoutOutliers(OutlierMode outlierMode, List<double> measurements,
double lowerFence, double upperFence, out double sum, out int n)
{
sum = 0;
n = 0;
foreach (var m in measurements)
{
if (!IsOutlier(outlierMode, m, lowerFence, upperFence))
{
sum += m;
++n;
}
}
}
static double Variance(List<double> measurements, int n, double mean)
{
if (n == 1)
{
return 0;
}
double variance = 0;
foreach (var m in measurements)
{
variance += (m - mean) * (m - mean) / (n - 1);
}
return variance;
}
static double VarianceWithoutOutliers(OutlierMode outlierMode, List<double> measurements, int n, double mean, double lowerFence, double upperFence)
{
if (n == 1)
{
return 0;
}
double variance = 0;
foreach (var m in measurements)
{
if (!IsOutlier(outlierMode, m, lowerFence, upperFence))
{
variance += (m - mean) * (m - mean) / (n - 1);
}
}
return variance;
}
static double GetQuartile(List<double> measurements, int count)
{
if (count % 2 == 0)
{
return (measurements[count / 2 - 1] + measurements[count / 2]) / 2;
}
return measurements[count / 2];
}
static bool IsOutlier(OutlierMode outlierMode, double value, double lowerFence, double upperFence)
{
switch (outlierMode)
{
case OutlierMode.DontRemove:
return false;
case OutlierMode.Remove:
return value < lowerFence || value > upperFence;
default:
throw new ArgumentOutOfRangeException(nameof(outlierMode), outlierMode, "Unknown OutlierMode value.");
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2677a59243824b90add157da8988edde
timeCreated: 1634592506
@@ -0,0 +1,54 @@
using System;
using static System.Math;
namespace Unity.PerformanceTesting.Statistics
{
static class NormalDistributionHelper
{
/// <summary>
/// ACM Algorithm 209: Gauss
///
/// Calculates $(1/\sqrt{2\pi}) \int_{-\infty}^x e^{-u^2 / 2} du$
/// by means of polynomial approximations due to A. M. Murray of Aberdeen University;
///
/// See: http://dl.acm.org/citation.cfm?id=367664
/// </summary>
/// <param name="x">-infinity..+infinity</param>
/// <returns>Area under the Standard Normal Curve from -infinity to x</returns>
public static double Gauss(double x)
{
double z;
if (Abs(x) < 1e-9)
z = 0.0;
else
{
var y = Abs(x) / 2;
if (y >= 3.0)
z = 1.0;
else if (y < 1.0)
{
var w = y * y;
z = ((((((((0.000124818987 * w - 0.001075204047) * w
+ 0.005198775019) * w - 0.019198292004) * w
+ 0.059054035642) * w - 0.151968751364) * w
+ 0.319152932694) * w - 0.531923007300) * w
+ 0.797884560593) * y * 2.0;
}
else
{
y = y - 2.0;
z = (((((((((((((-0.000045255659 * y + 0.000152529290) * y
- 0.000019538132) * y - 0.000676904986) * y
+ 0.001390604284) * y - 0.000794620820) * y
- 0.002034254874) * y + 0.006549791214) * y
- 0.010557625006) * y + 0.011630447319) * y
- 0.009279453341) * y + 0.005353579108) * y
- 0.002141268741) * y + 0.000535310849) * y
+ 0.999936657524;
}
}
return x > 0.0 ? (z + 1.0) / 2 : (1.0 - z) / 2;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: fe39db111ce84f2b933e63e8cced3493
timeCreated: 1634592935
@@ -0,0 +1,20 @@
using System;
namespace Unity.PerformanceTesting.Statistics
{
/// <summary>
/// Outlier removal mode.
/// </summary>
public enum OutlierMode
{
/// <summary>
/// Do not remove outliers.
/// </summary>
DontRemove,
/// <summary>
/// Remove outliers using the Tukey fences method.
/// </summary>
Remove
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: ba96708fc5e040b3b480033a77f69343
timeCreated: 1634586537
@@ -0,0 +1,102 @@
using System;
using static System.Math;
namespace Unity.PerformanceTesting.Statistics
{
static class StudentDistributionHelper
{
public static double InverseTwoTailedStudent(double p, double n)
{
var lower = 0.0;
var upper = 1000.0;
while (upper - lower > 1e-9)
{
var t = (lower + upper) / 2;
var p2 = TwoTailedStudent(t, n);
if (p2 < p)
upper = t;
else
lower = t;
}
return (lower + upper) / 2;
}
/// <summary>
/// ACM Algorithm 395: Student's t-distribution
///
/// Evaluates the two-tail probability P(t|n) that t is exceeded
/// in magnitude for Student's t-distribution with n degrees of freedom.
///
/// http://dl.acm.org/citation.cfm?id=355599
/// </summary>
/// <param name="t">t-value, t > 0</param>
/// <param name="n">Degree of freedom, n >= 1</param>
/// <returns>2-tail p-value</returns>
static double TwoTailedStudent(double t, double n)
{
if (t < 0)
throw new ArgumentOutOfRangeException(nameof(t), "t should be >= 0");
if (n < 1)
throw new ArgumentOutOfRangeException(nameof(n), "n should be >= 1");
t = t * t;
var y = t / n;
var b = y + 1.0;
var nn = (int)Round(n);
if (Abs(n - nn) > 1e-9 || n >= 20 || t < n && n > 200)
{
if (y > 1.0e-6)
y = Log(b);
var a = n - 0.5;
b = 48.0 * (a * a);
y = a * y;
y = (((((-0.4 * y - 3.3) * y - 24.0) * y - 85.5) / (0.8 * (y * y) + 100.0 + b) + y + 3.0) / b + 1.0) * Sqrt(y);
return 2 * NormalDistributionHelper.Gauss(-y);
}
{
double z = 1;
double a;
if (n < 20 && t < 4.0)
{
y = Sqrt(y);
a = y;
if (nn == 1)
a = 0;
}
else
{
a = Sqrt(b);
y = a * nn;
var j = 0;
while (Abs(a - z) > 0)
{
j += 2;
z = a;
y *= (j - 1) / (b * j);
a += y / (nn + j);
}
nn += 2;
z = 0;
y = 0;
a = -a;
}
while (true)
{
nn -= 2;
if (nn > 1)
a = (nn - 1) / (b * nn) * a + y;
else
break;
}
a = nn == 0 ? a / Sqrt(b) : (Atan(y) + a / b) * 2 / PI;
return z - a;
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 0f798be1803b48ecaf2670b1cbbc41b1
timeCreated: 1634592898
@@ -0,0 +1,27 @@
{
"name": "Unity.PerformanceTesting",
"rootNamespace": "",
"references": [
"UnityEngine.TestRunner",
"com.unity.test.metadata-manager"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": true,
"precompiledReferences": [
"nunit.framework.dll"
],
"autoReferenced": false,
"defineConstraints": [
"UNITY_TESTS_FRAMEWORK"
],
"versionDefines": [
{
"name": "com.unity.test-framework",
"expression": "",
"define": "UNITY_TESTS_FRAMEWORK"
}
],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: c0dd0d10738d4ad4a9de57c559d0ca1b
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,243 @@
using System;
using System.Collections.Generic;
using System.IO;
using Unity.PerformanceTesting.Exceptions;
using UnityEngine;
namespace Unity.PerformanceTesting.Runtime
{
internal static class Utils
{
public static string ResourcesPath => Path.Combine(Application.dataPath, "Resources");
public const string TestRunPath = "Assets/Resources/" + TestRunInfo;
public const string TestRunInfo = "PerformanceTestRunInfo.json";
public const string PlayerPrefKeyRunJSON = "PT_Run";
public const string RunSettingsPath = "Assets/Resources/" + RunSettings;
public const string RunSettings = "PerformanceTestRunSettings.json";
public const string PlayerPrefKeySettingsJSON = "PT_Settings";
public static DateTime ConvertFromUnixTimestamp(long timestamp)
{
var offset = DateTimeOffset.FromUnixTimeMilliseconds(timestamp);
return offset.UtcDateTime;
}
public static long ConvertToUnixTimestamp(DateTime date)
{
var offset = new DateTimeOffset(date);
return offset.ToUnixTimeMilliseconds();
}
public static double ConvertSample(SampleUnit from, SampleUnit to, double value)
{
if (from == to) return value;
var ratio = GetRatio(from, to);
return value * ratio;
}
public static double GetRatio(SampleUnit from, SampleUnit to)
{
double f = RelativeSampleUnit(from);
double t = RelativeSampleUnit(to);
return f / t;
}
public static double RelativeSampleUnit(SampleUnit unit)
{
switch (unit)
{
case SampleUnit.Nanosecond:
return 1;
case SampleUnit.Microsecond:
return 1000;
case SampleUnit.Millisecond:
return 1000000;
case SampleUnit.Second:
return 1000000000;
case SampleUnit.Byte:
return 1;
case SampleUnit.Kilobyte:
return 1000;
case SampleUnit.Megabyte:
return 1000000;
case SampleUnit.Gigabyte:
return 1000000000;
default:
throw new PerformanceTestException(
"Wrong SampleUnit type used.");
}
}
public static void UpdateStatistics(this SampleGroup sampleGroup)
{
if (sampleGroup.Samples == null) return;
var samples = sampleGroup.Samples;
if (samples.Count == 0)
{
// A sample group can be registered without ever receiving a sample - through the public
// AddSampleGroup API, or by a measurement whose measurement count resolves to zero. Report
// it with zeroed statistics instead of indexing an empty list.
sampleGroup.Min = 0;
sampleGroup.Max = 0;
sampleGroup.Median = 0;
sampleGroup.Average = 0;
sampleGroup.Sum = 0;
sampleGroup.StandardDeviation = 0;
}
else if (samples.Count == 1)
{
sampleGroup.Min = samples[0];
sampleGroup.Max = samples[0];
sampleGroup.Median = samples[0];
sampleGroup.Average = samples[0];
sampleGroup.Sum = samples[0];
sampleGroup.StandardDeviation = 0;
}
else
{
sampleGroup.Min = Utils.Min(samples);
sampleGroup.Max = Utils.Max(samples);
sampleGroup.Median = Utils.GetMedianValue(samples);
sampleGroup.Average = Utils.Average(samples);
sampleGroup.Sum = Utils.Sum(samples);
sampleGroup.StandardDeviation = Utils.GetStandardDeviation(samples, sampleGroup.Average);
}
}
public static int GetZeroValueCount(List<double> samples)
{
var zeroValues = 0;
foreach (var sample in samples)
{
if (Math.Abs(sample) < .0001f)
{
zeroValues++;
}
}
return zeroValues;
}
public static double GetMedianValue(List<double> samples)
{
var samplesClone = new List<double>(samples);
var middleIndex = samplesClone.Count / 2;
samplesClone.Sort();
return samplesClone.Count % 2 != 0
? samplesClone[middleIndex]
: (samplesClone[middleIndex - 1] + samplesClone[middleIndex]) / 2.0;
}
public static double GetPercentile(List<double> samples, double percentile)
{
if (percentile < 0.00001D)
return percentile;
var samplesClone = new List<double>(samples);
samplesClone.Sort();
if (samplesClone.Count == 1)
{
return samplesClone[0];
}
var rank = percentile * (samplesClone.Count + 1);
var integral = (int)rank;
var fractional = rank % 1;
return samplesClone[integral - 1] + fractional * (samplesClone[integral] - samplesClone[integral - 1]);
}
public static double GetStandardDeviation(List<double> samples, double average)
{
double sumOfSquaresOfDifferences = 0.0D;
foreach (var sample in samples)
{
sumOfSquaresOfDifferences += (sample - average) * (sample - average);
}
return Math.Sqrt(sumOfSquaresOfDifferences / samples.Count);
}
public static double Min(List<double> samples)
{
double min = Mathf.Infinity;
foreach (var sample in samples)
{
if (sample < min) min = sample;
}
return min;
}
public static double Max(List<double> samples)
{
double max = Mathf.NegativeInfinity;
foreach (var sample in samples)
{
if (sample > max) max = sample;
}
return max;
}
public static double Average(List<double> samples)
{
return Sum(samples) / samples.Count;
}
public static double Sum(List<double> samples)
{
double sum = 0.0D;
foreach (var sample in samples)
{
sum += sample;
}
return sum;
}
public static string RemoveIllegalCharacters(string path)
{
string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
foreach (char c in invalid)
{
path = path.Replace(c.ToString(), "");
}
return path;
}
public static string GetArg(string[] args, string name)
{
for (int i = 0; i < args.Length; i++)
{
if (args[i] == name && args.Length > i + 1)
{
return args[i + 1];
}
}
return null;
}
internal static int ToInt(this string s)
{
if (int.TryParse(s, out var i)) return i;
return -1;
}
internal static SampleGroup[] CreateSampleGroupsFromMarkerNames(params string[] profilerMarkerNames)
{
if (profilerMarkerNames == null) return new List<SampleGroup>().ToArray();
var sampleGroups = new List<SampleGroup>();
foreach (var marker in profilerMarkerNames)
{
sampleGroups.Add(new SampleGroup(marker, SampleUnit.Nanosecond, false));
}
return sampleGroups.ToArray();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7dd61a6c0836b0145836c05f91470e99
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: