Brak opisu
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.

ProfilingScope.cs 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. // TProfilingSampler<TEnum>.samples should just be an array. Unfortunately, Enum cannot be converted to int without generating garbage.
  2. // This could be worked around by using Unsafe but it's not available at the moment.
  3. // So in the meantime we use a Dictionary with a perf hit...
  4. //#define USE_UNSAFE
  5. #if UNITY_2020_1_OR_NEWER
  6. #define UNITY_USE_RECORDER
  7. #endif
  8. using System;
  9. using System.Linq;
  10. using System.Collections.Generic;
  11. using UnityEngine.Profiling;
  12. using Unity.Profiling;
  13. namespace UnityEngine.Rendering
  14. {
  15. class TProfilingSampler<TEnum> : ProfilingSampler where TEnum : Enum
  16. {
  17. #if USE_UNSAFE
  18. internal static TProfilingSampler<TEnum>[] samples;
  19. #else
  20. internal static Dictionary<TEnum, TProfilingSampler<TEnum>> samples = new Dictionary<TEnum, TProfilingSampler<TEnum>>();
  21. #endif
  22. static TProfilingSampler()
  23. {
  24. var names = Enum.GetNames(typeof(TEnum));
  25. #if USE_UNSAFE
  26. var values = Enum.GetValues(typeof(TEnum)).Cast<int>().ToArray();
  27. samples = new TProfilingSampler<TEnum>[values.Max() + 1];
  28. #else
  29. var values = Enum.GetValues(typeof(TEnum));
  30. #endif
  31. for (int i = 0; i < names.Length; i++)
  32. {
  33. var sample = new TProfilingSampler<TEnum>(names[i]);
  34. #if USE_UNSAFE
  35. samples[values[i]] = sample;
  36. #else
  37. samples.Add((TEnum)values.GetValue(i), sample);
  38. #endif
  39. }
  40. }
  41. public TProfilingSampler(string name)
  42. : base(name)
  43. {
  44. }
  45. }
  46. /// <summary>
  47. /// Wrapper around CPU and GPU profiling samplers.
  48. /// Use this along ProfilingScope to profile a piece of code.
  49. /// </summary>
  50. [IgnoredByDeepProfiler]
  51. public class ProfilingSampler
  52. {
  53. /// <summary>
  54. /// Get the sampler for the corresponding enumeration value.
  55. /// </summary>
  56. /// <typeparam name="TEnum">Type of the enumeration.</typeparam>
  57. /// <param name="marker">Enumeration value.</param>
  58. /// <returns>The profiling sampler for the given enumeration value.</returns>
  59. #if DEVELOPMENT_BUILD || UNITY_EDITOR
  60. public static ProfilingSampler Get<TEnum>(TEnum marker)
  61. where TEnum : Enum
  62. {
  63. #if USE_UNSAFE
  64. return TProfilingSampler<TEnum>.samples[Unsafe.As<TEnum, int>(ref marker)];
  65. #else
  66. TProfilingSampler<TEnum>.samples.TryGetValue(marker, out var sampler);
  67. return sampler;
  68. #endif
  69. }
  70. #else
  71. public static ProfilingSampler Get<TEnum>(TEnum marker)
  72. where TEnum : Enum
  73. {
  74. return null;
  75. }
  76. #endif
  77. /// <summary>
  78. /// Constructor.
  79. /// </summary>
  80. /// <param name="name">Name of the profiling sampler.</param>
  81. public ProfilingSampler(string name)
  82. {
  83. // Caution: Name of sampler MUST not match name provide to cmd.BeginSample(), otherwise
  84. // we get a mismatch of marker when enabling the profiler.
  85. #if UNITY_USE_RECORDER
  86. sampler = CustomSampler.Create(name, true); // Event markers, command buffer CPU profiling and GPU profiling
  87. #else
  88. // In this case, we need to use the BeginSample(string) API, since it creates a new sampler by that name under the hood,
  89. // we need rename this sampler to not clash with the implicit one (it won't be used in this case)
  90. sampler = CustomSampler.Create($"Dummy_{name}");
  91. #endif
  92. inlineSampler = CustomSampler.Create($"Inl_{name}"); // Profiles code "immediately"
  93. this.name = name;
  94. #if UNITY_USE_RECORDER
  95. m_Recorder = sampler.GetRecorder();
  96. m_Recorder.enabled = false;
  97. m_InlineRecorder = inlineSampler.GetRecorder();
  98. m_InlineRecorder.enabled = false;
  99. #endif
  100. }
  101. /// <summary>
  102. /// Begin the profiling block.
  103. /// </summary>
  104. /// <param name="cmd">Command buffer used by the profiling block.</param>
  105. public void Begin(CommandBuffer cmd)
  106. {
  107. if (cmd != null)
  108. #if UNITY_USE_RECORDER
  109. if (sampler != null && sampler.isValid)
  110. cmd.BeginSample(sampler);
  111. else
  112. cmd.BeginSample(name);
  113. #else
  114. cmd.BeginSample(name);
  115. #endif
  116. inlineSampler?.Begin();
  117. }
  118. /// <summary>
  119. /// End the profiling block.
  120. /// </summary>
  121. /// <param name="cmd">Command buffer used by the profiling block.</param>
  122. public void End(CommandBuffer cmd)
  123. {
  124. if (cmd != null)
  125. #if UNITY_USE_RECORDER
  126. if (sampler != null && sampler.isValid)
  127. cmd.EndSample(sampler);
  128. else
  129. cmd.EndSample(name);
  130. #else
  131. m_Cmd.EndSample(name);
  132. #endif
  133. inlineSampler?.End();
  134. }
  135. internal bool IsValid() { return (sampler != null && inlineSampler != null); }
  136. internal CustomSampler sampler { get; private set; }
  137. internal CustomSampler inlineSampler { get; private set; }
  138. /// <summary>
  139. /// Name of the Profiling Sampler
  140. /// </summary>
  141. public string name { get; private set; }
  142. #if UNITY_USE_RECORDER
  143. Recorder m_Recorder;
  144. Recorder m_InlineRecorder;
  145. #endif
  146. /// <summary>
  147. /// Set to true to enable recording of profiling sampler timings.
  148. /// </summary>
  149. public bool enableRecording
  150. {
  151. set
  152. {
  153. #if UNITY_USE_RECORDER
  154. m_Recorder.enabled = value;
  155. m_InlineRecorder.enabled = value;
  156. #endif
  157. }
  158. }
  159. #if UNITY_USE_RECORDER
  160. /// <summary>
  161. /// GPU Elapsed time in milliseconds.
  162. /// </summary>
  163. public float gpuElapsedTime => m_Recorder.enabled ? m_Recorder.gpuElapsedNanoseconds / 1000000.0f : 0.0f;
  164. /// <summary>
  165. /// Number of times the Profiling Sampler has hit on the GPU
  166. /// </summary>
  167. public int gpuSampleCount => m_Recorder.enabled ? m_Recorder.gpuSampleBlockCount : 0;
  168. /// <summary>
  169. /// CPU Elapsed time in milliseconds (Command Buffer execution).
  170. /// </summary>
  171. public float cpuElapsedTime => m_Recorder.enabled ? m_Recorder.elapsedNanoseconds / 1000000.0f : 0.0f;
  172. /// <summary>
  173. /// Number of times the Profiling Sampler has hit on the CPU in the command buffer.
  174. /// </summary>
  175. public int cpuSampleCount => m_Recorder.enabled ? m_Recorder.sampleBlockCount : 0;
  176. /// <summary>
  177. /// CPU Elapsed time in milliseconds (Direct execution).
  178. /// </summary>
  179. public float inlineCpuElapsedTime => m_InlineRecorder.enabled ? m_InlineRecorder.elapsedNanoseconds / 1000000.0f : 0.0f;
  180. /// <summary>
  181. /// Number of times the Profiling Sampler has hit on the CPU.
  182. /// </summary>
  183. public int inlineCpuSampleCount => m_InlineRecorder.enabled ? m_InlineRecorder.sampleBlockCount : 0;
  184. #else
  185. /// <summary>
  186. /// GPU Elapsed time in milliseconds.
  187. /// </summary>
  188. public float gpuElapsedTime => 0.0f;
  189. /// <summary>
  190. /// Number of times the Profiling Sampler has hit on the GPU
  191. /// </summary>
  192. public int gpuSampleCount => 0;
  193. /// <summary>
  194. /// CPU Elapsed time in milliseconds (Command Buffer execution).
  195. /// </summary>
  196. public float cpuElapsedTime => 0.0f;
  197. /// <summary>
  198. /// Number of times the Profiling Sampler has hit on the CPU in the command buffer.
  199. /// </summary>
  200. public int cpuSampleCount => 0;
  201. /// <summary>
  202. /// CPU Elapsed time in milliseconds (Direct execution).
  203. /// </summary>
  204. public float inlineCpuElapsedTime => 0.0f;
  205. /// <summary>
  206. /// Number of times the Profiling Sampler has hit on the CPU.
  207. /// </summary>
  208. public int inlineCpuSampleCount => 0;
  209. #endif
  210. // Keep the constructor private
  211. ProfilingSampler() { }
  212. }
  213. #if DEVELOPMENT_BUILD || UNITY_EDITOR
  214. /// <summary>
  215. /// Scoped Profiling markers
  216. /// </summary>
  217. [IgnoredByDeepProfiler]
  218. public struct ProfilingScope : IDisposable
  219. {
  220. CommandBuffer m_Cmd;
  221. bool m_Disposed;
  222. ProfilingSampler m_Sampler;
  223. /// <summary>
  224. /// Profiling Scope constructor
  225. /// </summary>
  226. /// <param name="sampler">Profiling Sampler to be used for this scope.</param>
  227. public ProfilingScope(ProfilingSampler sampler)
  228. {
  229. m_Cmd = null;
  230. m_Disposed = false;
  231. m_Sampler = sampler;
  232. m_Sampler?.Begin(m_Cmd);
  233. }
  234. /// <summary>
  235. /// Profiling Scope constructor
  236. /// </summary>
  237. /// <param name="cmd">Command buffer used to add markers and compute execution timings.</param>
  238. /// <param name="sampler">Profiling Sampler to be used for this scope.</param>
  239. public ProfilingScope(CommandBuffer cmd, ProfilingSampler sampler)
  240. {
  241. // NOTE: Do not mix with named CommandBuffers.
  242. // Currently there's an issue which results in mismatched markers.
  243. // The named CommandBuffer will close its "profiling scope" on execution.
  244. // That will orphan ProfilingScope markers as the named CommandBuffer marker
  245. // is their "parent".
  246. // Resulting in following pattern:
  247. // exec(cmd.start, scope.start, cmd.end) and exec(cmd.start, scope.end, cmd.end)
  248. m_Cmd = cmd;
  249. m_Disposed = false;
  250. m_Sampler = sampler;
  251. m_Sampler?.Begin(m_Cmd);
  252. }
  253. /// <summary>
  254. /// Profiling Scope constructor
  255. /// </summary>
  256. /// <param name="cmd">Command buffer used to add markers and compute execution timings.</param>
  257. /// <param name="sampler">Profiling Sampler to be used for this scope.</param>
  258. public ProfilingScope(BaseCommandBuffer cmd, ProfilingSampler sampler)
  259. {
  260. // NOTE: Do not mix with named CommandBuffers.
  261. // Currently there's an issue which results in mismatched markers.
  262. // The named CommandBuffer will close its "profiling scope" on execution.
  263. // That will orphan ProfilingScope markers as the named CommandBuffer marker
  264. // is their "parent".
  265. // Resulting in following pattern:
  266. // exec(cmd.start, scope.start, cmd.end) and exec(cmd.start, scope.end, cmd.end)
  267. m_Cmd = cmd.m_WrappedCommandBuffer;
  268. m_Disposed = false;
  269. m_Sampler = sampler;
  270. m_Sampler?.Begin(m_Cmd);
  271. }
  272. /// <summary>
  273. /// Dispose pattern implementation
  274. /// </summary>
  275. public void Dispose()
  276. {
  277. Dispose(true);
  278. }
  279. // Protected implementation of Dispose pattern.
  280. void Dispose(bool disposing)
  281. {
  282. if (m_Disposed)
  283. return;
  284. // As this is a struct, it could have been initialized using an empty constructor so we
  285. // need to make sure `cmd` isn't null to avoid a crash. Switching to a class would fix
  286. // this but will generate garbage on every frame (and this struct is used quite a lot).
  287. if (disposing)
  288. {
  289. m_Sampler?.End(m_Cmd);
  290. }
  291. m_Disposed = true;
  292. }
  293. }
  294. #else
  295. /// <summary>
  296. /// Scoped Profiling markers
  297. /// </summary>
  298. public struct ProfilingScope : IDisposable
  299. {
  300. /// <summary>
  301. /// Profiling Scope constructor
  302. /// </summary>
  303. /// <param name="sampler">Profiling Sampler to be used for this scope.</param>
  304. public ProfilingScope(ProfilingSampler sampler)
  305. {
  306. }
  307. /// <summary>
  308. /// Profiling Scope constructor
  309. /// </summary>
  310. /// <param name="cmd">Command buffer used to add markers and compute execution timings.</param>
  311. /// <param name="sampler">Profiling Sampler to be used for this scope.</param>
  312. public ProfilingScope(CommandBuffer cmd, ProfilingSampler sampler)
  313. {
  314. }
  315. /// <summary>
  316. /// Profiling Scope constructor
  317. /// </summary>
  318. /// <param name="cmd">Command buffer used to add markers and compute execution timings.</param>
  319. /// <param name="sampler">Profiling Sampler to be used for this scope.</param>
  320. public ProfilingScope(BaseCommandBuffer cmd, ProfilingSampler sampler)
  321. {
  322. }
  323. /// <summary>
  324. /// Dispose pattern implementation
  325. /// </summary>
  326. public void Dispose()
  327. {
  328. }
  329. }
  330. #endif
  331. /// <summary>
  332. /// Profiling Sampler class.
  333. /// </summary>
  334. [System.Obsolete("Please use ProfilingScope")]
  335. [IgnoredByDeepProfiler]
  336. public struct ProfilingSample : IDisposable
  337. {
  338. readonly CommandBuffer m_Cmd;
  339. readonly string m_Name;
  340. bool m_Disposed;
  341. CustomSampler m_Sampler;
  342. /// <summary>
  343. /// Constructor
  344. /// </summary>
  345. /// <param name="cmd">Command Buffer.</param>
  346. /// <param name="name">Name of the profiling sample.</param>
  347. /// <param name="sampler">Custom sampler for CPU profiling.</param>
  348. public ProfilingSample(CommandBuffer cmd, string name, CustomSampler sampler = null)
  349. {
  350. m_Cmd = cmd;
  351. m_Name = name;
  352. m_Disposed = false;
  353. if (cmd != null && name != "")
  354. cmd.BeginSample(name);
  355. m_Sampler = sampler;
  356. m_Sampler?.Begin();
  357. }
  358. // Shortcut to string.Format() using only one argument (reduces Gen0 GC pressure)
  359. /// <summary>
  360. /// Constructor
  361. /// </summary>
  362. /// <param name="cmd">Command Buffer.</param>
  363. /// <param name="format">Formating of the profiling sample.</param>
  364. /// <param name="arg">Parameters for formating the name.</param>
  365. public ProfilingSample(CommandBuffer cmd, string format, object arg) : this(cmd, string.Format(format, arg))
  366. {
  367. }
  368. // Shortcut to string.Format() with variable amount of arguments - for performance critical
  369. // code you should pre-build & cache the marker name instead of using this
  370. /// <summary>
  371. /// Constructor.
  372. /// </summary>
  373. /// <param name="cmd">Command Buffer.</param>
  374. /// <param name="format">Formating of the profiling sample.</param>
  375. /// <param name="args">Parameters for formating the name.</param>
  376. public ProfilingSample(CommandBuffer cmd, string format, params object[] args) : this(cmd, string.Format(format, args))
  377. {
  378. }
  379. /// <summary>
  380. /// Dispose pattern implementation
  381. /// </summary>
  382. public void Dispose()
  383. {
  384. Dispose(true);
  385. }
  386. // Protected implementation of Dispose pattern.
  387. void Dispose(bool disposing)
  388. {
  389. if (m_Disposed)
  390. return;
  391. // As this is a struct, it could have been initialized using an empty constructor so we
  392. // need to make sure `cmd` isn't null to avoid a crash. Switching to a class would fix
  393. // this but will generate garbage on every frame (and this struct is used quite a lot).
  394. if (disposing)
  395. {
  396. if (m_Cmd != null && m_Name != "")
  397. m_Cmd.EndSample(m_Name);
  398. m_Sampler?.End();
  399. }
  400. m_Disposed = true;
  401. }
  402. }
  403. }