No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FramesMeasurement.cs 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. using System;
  2. using System.Collections;
  3. using System.Diagnostics;
  4. using Unity.PerformanceTesting.Data;
  5. using Unity.PerformanceTesting.Runtime;
  6. using Unity.PerformanceTesting.Statistics;
  7. using UnityEngine;
  8. using Debug = UnityEngine.Debug;
  9. using Object = UnityEngine.Object;
  10. namespace Unity.PerformanceTesting.Measurements
  11. {
  12. /// <summary>
  13. /// Allows measuring of frame times.
  14. /// </summary>
  15. public class FramesMeasurement
  16. {
  17. private const int k_MinTestTimeMs = 500;
  18. private const int k_MinWarmupTimeMs = 80;
  19. private const int k_ProbingMultiplier = 4;
  20. internal const int k_MinIterations = 7;
  21. internal const int k_MaxDynamicMeasurements = 1000;
  22. private const double k_DefaultMaxRelativeError = 0.02;
  23. private const ConfidenceLevel k_DefaultConfidenceLevel = ConfidenceLevel.L99;
  24. private const OutlierMode k_DefaultOutlierMode = OutlierMode.Remove;
  25. private SampleGroup[] m_ProfilerSampleGroups;
  26. private SampleGroup m_SampleGroup = new SampleGroup("FrameTime");
  27. private int m_DesiredFrameCount;
  28. internal bool m_DynamicMeasurementCount;
  29. private double m_MaxRelativeError = k_DefaultMaxRelativeError;
  30. private ConfidenceLevel m_ConfidenceLevel = k_DefaultConfidenceLevel;
  31. private OutlierMode m_OutlierMode = k_DefaultOutlierMode;
  32. private int m_Executions;
  33. private int m_Warmup = -1;
  34. private bool m_RecordFrametime = true;
  35. /// <summary>
  36. /// Records provided profiler markers once per frame.
  37. /// </summary>
  38. /// <param name="profilerMarkerNames">Profiler marker names as in profiler window.</param>
  39. /// <returns></returns>
  40. public FramesMeasurement ProfilerMarkers(params string[] profilerMarkerNames)
  41. {
  42. m_ProfilerSampleGroups = Utils.CreateSampleGroupsFromMarkerNames(profilerMarkerNames);
  43. return this;
  44. }
  45. /// <summary>
  46. /// Records provided profiler markers once per frame.
  47. /// </summary>
  48. /// <param name="sampleGroups">List of SampleGroups where a name matches the profiler marker and desired SampleUnit</param>
  49. /// <returns></returns>
  50. public FramesMeasurement ProfilerMarkers(params SampleGroup[] sampleGroups)
  51. {
  52. m_ProfilerSampleGroups = sampleGroups;
  53. return this;
  54. }
  55. /// <summary>
  56. /// Overrides the name of default sample group "Time".
  57. /// </summary>
  58. /// <param name="name">Name of the sample group.</param>
  59. /// <returns></returns>
  60. public FramesMeasurement SampleGroup(string name)
  61. {
  62. m_SampleGroup.Name = name;
  63. return this;
  64. }
  65. /// <summary>
  66. /// Overrides the default sample group "Time"
  67. /// </summary>
  68. /// <param name="sampleGroup">Sample group to use.</param>
  69. /// <returns></returns>
  70. public FramesMeasurement SampleGroup(SampleGroup sampleGroup)
  71. {
  72. m_SampleGroup = sampleGroup;
  73. return this;
  74. }
  75. /// <summary>
  76. /// Count of measurements to take.
  77. /// </summary>
  78. /// <param name="count">Count of measurements.</param>
  79. /// <returns></returns>
  80. public FramesMeasurement MeasurementCount(int count)
  81. {
  82. m_Executions = count;
  83. return this;
  84. }
  85. /// <summary>
  86. /// Dynamically find a suitable measurement count based on the margin of error of the samples.
  87. /// The measurements will stop once a certain amount of samples (specified by a confidence interval)
  88. /// falls within an acceptable error range from the result (defined by a relative error of the mean).
  89. /// A default margin of error range of 2% and a default confidence interval of 99% will be used.
  90. /// </summary>
  91. /// <param name="outlierMode">Outlier mode allows to include or exclude outliers when evaluating the stop criterion.</param>
  92. /// <returns></returns>
  93. public FramesMeasurement DynamicMeasurementCount(OutlierMode outlierMode = k_DefaultOutlierMode)
  94. {
  95. m_DynamicMeasurementCount = true;
  96. m_OutlierMode = outlierMode;
  97. return this;
  98. }
  99. /// <summary>
  100. /// Dynamically find a suitable measurement count based on the margin of error of the samples.
  101. /// The measurements will stop once a certain amount of samples (specified by a confidence interval)
  102. /// falls within an acceptable error range from the result (defined by a relative error of the mean).
  103. /// </summary>
  104. /// <param name="maxRelativeError">The maximum relative error of the mean that the margin of error must fall into.</param>
  105. /// <param name="confidenceLevel">The confidence interval which will be used to calculate the margin of error.</param>
  106. /// <param name="outlierMode">Outlier mode allows to include or exclude outliers when evaluating the stop criterion.</param>
  107. /// <returns></returns>
  108. public FramesMeasurement DynamicMeasurementCount(double maxRelativeError, ConfidenceLevel confidenceLevel = k_DefaultConfidenceLevel,
  109. OutlierMode outlierMode = k_DefaultOutlierMode)
  110. {
  111. m_MaxRelativeError = maxRelativeError;
  112. m_ConfidenceLevel = confidenceLevel;
  113. m_DynamicMeasurementCount = true;
  114. m_OutlierMode = outlierMode;
  115. return this;
  116. }
  117. /// <summary>
  118. /// Count of warmup executions.
  119. /// </summary>
  120. /// <param name="count">Count of warmup executions.</param>
  121. /// <returns></returns>
  122. public FramesMeasurement WarmupCount(int count)
  123. {
  124. m_Warmup = count;
  125. return this;
  126. }
  127. /// <summary>
  128. /// Specifies frame times should not be recorded.
  129. /// </summary>
  130. /// <returns></returns>
  131. public FramesMeasurement DontRecordFrametime()
  132. {
  133. m_RecordFrametime = false;
  134. return this;
  135. }
  136. /// <summary>
  137. /// Switches frame time measurement to asynchronous scope measurement.
  138. /// </summary>
  139. /// <param name="name">Sample group name.</param>
  140. /// <returns></returns>
  141. public ScopedFrameTimeMeasurement Scope(string name = "Time")
  142. {
  143. return new ScopedFrameTimeMeasurement(name);
  144. }
  145. /// <summary>
  146. /// Switches frame time measurement to asynchronous scope measurement.
  147. /// </summary>
  148. /// <param name="sampleGroup">Sample group to save measurements.</param>
  149. /// <returns></returns>
  150. public ScopedFrameTimeMeasurement Scope(SampleGroup sampleGroup)
  151. {
  152. return new ScopedFrameTimeMeasurement(sampleGroup);
  153. }
  154. /// <summary>
  155. /// Executes the frame time measurement with given parameters. When MeasurementCount is not provided, a probing method will run to determine desired measurement counts.
  156. /// </summary>
  157. /// <returns>IEnumerator to yield until finish.</returns>
  158. public IEnumerator Run()
  159. {
  160. ValidateCorrectDynamicMeasurementCountUsage();
  161. if (!ValidateMeasurementAndWarmupCount()) yield break;
  162. SettingsOverride();
  163. yield return m_Warmup > -1 ? WaitFor(m_Warmup) : GetDesiredIterationCount();
  164. using (Measure.ProfilerMarkers(m_ProfilerSampleGroups))
  165. {
  166. if (m_DynamicMeasurementCount)
  167. {
  168. yield return RunDynamicMeasurementCount();
  169. }
  170. else
  171. {
  172. yield return RunFixedMeasurementCount();
  173. }
  174. // WaitForEndOfFrame coroutine is not invoked on the editor in batch mode
  175. // This may lead to unexpected behavior and is better to avoid
  176. // https://docs.unity3d.com/ScriptReference/WaitForEndOfFrame.html
  177. if (!Application.isBatchMode && Application.isPlaying)
  178. {
  179. yield return new WaitForEndOfFrame();
  180. }
  181. }
  182. }
  183. private IEnumerator RunDynamicMeasurementCount()
  184. {
  185. while (true)
  186. {
  187. using (Measure.Scope(m_SampleGroup))
  188. {
  189. yield return null;
  190. }
  191. if (SampleCountFulfillsRequirements())
  192. break;
  193. }
  194. }
  195. private IEnumerator RunFixedMeasurementCount()
  196. {
  197. m_DesiredFrameCount = m_Executions > 0 ? m_Executions : m_DesiredFrameCount;
  198. for (var i = 0; i < m_DesiredFrameCount; i++)
  199. {
  200. if (m_RecordFrametime)
  201. {
  202. using (Measure.Scope(m_SampleGroup))
  203. {
  204. yield return null;
  205. }
  206. }
  207. else
  208. {
  209. yield return null;
  210. }
  211. }
  212. }
  213. private bool ValidateMeasurementAndWarmupCount()
  214. {
  215. if (m_DynamicMeasurementCount || m_Executions != 0 || m_Warmup < 0) return true;
  216. Debug.LogError("Provide execution count or remove warmup count from frames measurement.");
  217. return false;
  218. }
  219. private void ValidateCorrectDynamicMeasurementCountUsage()
  220. {
  221. if (!m_DynamicMeasurementCount)
  222. return;
  223. if (m_Executions > 0)
  224. {
  225. m_DynamicMeasurementCount = false;
  226. Debug.LogWarning("DynamicMeasurementCount will be ignored because MeasurementCount was specified.");
  227. return;
  228. }
  229. if (!m_RecordFrametime)
  230. {
  231. m_DynamicMeasurementCount = false;
  232. Debug.LogWarning("DynamicMeasurementCount will be ignored because FrameTime measurement was disabled.");
  233. }
  234. }
  235. private bool SampleCountFulfillsRequirements()
  236. {
  237. var samples = m_SampleGroup.Samples;
  238. var sampleCount = samples.Count;
  239. var statistics = MeasurementsStatistics.Calculate(samples, m_OutlierMode, m_ConfidenceLevel);
  240. var actualError = statistics.MarginOfError;
  241. var maxError = m_MaxRelativeError * statistics.Mean;
  242. if (sampleCount >= k_MinIterations && actualError < maxError)
  243. return true;
  244. if (sampleCount >= k_MaxDynamicMeasurements)
  245. return true;
  246. return false;
  247. }
  248. /// <summary>
  249. /// Overrides measurement count based on performance run settings
  250. /// </summary>
  251. private void SettingsOverride()
  252. {
  253. var count = RunSettings.Instance.MeasurementCount;
  254. if (count < 0) { return; }
  255. m_Executions = count;
  256. m_Warmup = m_Warmup < 1 ? 0 : count;
  257. m_DynamicMeasurementCount = false;
  258. }
  259. private IEnumerator GetDesiredIterationCount()
  260. {
  261. var executionTime = 0.0D;
  262. var iterations = 1;
  263. while (executionTime < k_MinWarmupTimeMs)
  264. {
  265. var sw = Stopwatch.GetTimestamp();
  266. yield return WaitFor(iterations);
  267. executionTime = TimeSpan.FromTicks(Stopwatch.GetTimestamp() - sw).TotalMilliseconds;
  268. if (iterations == 1 && executionTime > 40)
  269. {
  270. m_DesiredFrameCount = k_MinIterations;
  271. yield break;
  272. }
  273. if (iterations == 64)
  274. {
  275. m_DesiredFrameCount = 120;
  276. yield break;
  277. }
  278. if (executionTime < k_MinWarmupTimeMs)
  279. {
  280. iterations *= k_ProbingMultiplier;
  281. }
  282. }
  283. m_DesiredFrameCount = (int)(k_MinTestTimeMs * iterations / executionTime);
  284. }
  285. private IEnumerator WaitFor(int iterations)
  286. {
  287. for (var i = 0; i < iterations; i++)
  288. {
  289. yield return null;
  290. }
  291. }
  292. /// <summary>
  293. /// Provides a way to measure frame time within a scope.
  294. /// </summary>
  295. public struct ScopedFrameTimeMeasurement : IDisposable
  296. {
  297. private readonly FrameTimeMeasurement m_Test;
  298. /// <summary>
  299. /// Initializes a scoped frame time measurement.
  300. /// </summary>
  301. /// <param name="sampleGroup">Sample group used to store measurements.</param>
  302. public ScopedFrameTimeMeasurement(SampleGroup sampleGroup)
  303. {
  304. var go = new GameObject("Recorder");
  305. if (Application.isPlaying) Object.DontDestroyOnLoad(go);
  306. m_Test = go.AddComponent<FrameTimeMeasurement>();
  307. m_Test.SampleGroup = sampleGroup;
  308. PerformanceTest.Disposables.Add(this);
  309. }
  310. /// <summary>
  311. /// Initializes a scoped frame time measurement.
  312. /// </summary>
  313. /// <param name="name">Sample group name used to store measurements.</param>
  314. public ScopedFrameTimeMeasurement(string name): this(new SampleGroup(name))
  315. {
  316. }
  317. /// <summary>
  318. /// Stops scoped frame time measurement and adds it to provided sample group.
  319. /// </summary>
  320. public void Dispose()
  321. {
  322. PerformanceTest.Disposables.Remove(this);
  323. Object.DestroyImmediate(m_Test.gameObject);
  324. }
  325. }
  326. }
  327. }