向代码中添加性能分析器Markers
Add Profiler分析Markers记来标记代码的区域。
阅读时间6 分钟最后更新于 10 天前
向代码添加性能分析器 Markers 可以查看性能分析器窗口中 CPU 使用率模块的 Time轴 View 和 Hierarchy 视图中、 或 生成的样本:
ProfilerMarker.BeginProfilerMarker.EndProfilerMarker.Auto
Profiler sample with metadata in Timeline View.

Profiler sample with metadata in Hierarchy View.
先决条件
一些示例使用性能分析核心包,必须在 Start 之前安装该包。在 Package Manager UI 中找不到 Unity Profiling Core 包,因为它是包。要安装该包,请添加其 Name,即 。
com.unity.profiling.core标记代码
using UnityEngine;using Unity.Profiling;public class ProfilerMarkerExample{ Static readonly ProfilerMarker k_MyCodeMarker = 新建 ProfilerMarker("My 代码"); void Update() { k_MyCodeMarker.Begin(); Debug.Log("This code is being profiled"); k_MyCodeMarker.End(); }}
确保在调用 之前, 和 Calls 之间的代码不会退出作用域。如果在调用 之前代码退出作用域,则会将报错 message 记录到控制台。为了避免在每次返回之前必须调用 ,请使用 ,以便样本离开作用域时自动结束。有关更多信息,请参阅本文档中的 ON 自动关闭性能分析器标记代码块部分。
EndBeginEndEndEndAutoUnity 将性能分析代码块的执行时间记录并报告给性能分析器,并将其显示在 CPU 性能分析器模块中,而无需使用深度性能分析。它将在 CPU 性能分析器模块的 Hierarchy 视图中显示为新建条目,如下所示:

Profiler sample in the Profiler Window.
自动关闭性能分析器记代代码
使用 确保在代码块结束时自动调用 。以下 Calls 是等效的:
ProfilerMarker.AutoProfilerMarker.Endusing Unity.Profiling;public class MySystemClass{ Static readonly ProfilerMarker k_UpdatePerfMarker = 新建 ProfilerMarker("更新"); public void Update() { k_UpdatePerfMarker.Begin(); // ... k_UpdatePerfMarker.End(); using (k_UpdatePerfMarker.自动()) { // ... } }}
与 和 Calls 不同,Unity 无法在非 Development(发布)版本中编译出 调用。但是,它将返回 null,这只会增加最少的开销。
Begin()End()ProfilerMarker.Auto还可以将与一起使用,并且一旦当前作用域结束,调用将自动发生。此方法可最大限度减少向代码添加实例时需要更改的代码量:
ProfilerMarker.Autousing varEndProfilerMarkerusing Unity.Profiling;public class MySystemClass{ Static readonly ProfilerMarker k_UpdatePerfMarker = 新建 ProfilerMarker("更新"); public void Update() { using var _ = 自动; // ... }}
向样本添加整数或点Parameters
有时,您可能希望向代码样本添加上下文,以确定代码长时间运行的指定的条件。
例如,如果System执行对象模拟,可使用性能分析器样本道对象的数量。如果性性能分析器返回异常数量以及较长的样本Duration,这可能意味着必须使用另一个线程进行模拟,将 CPU 工作拆分为多个个帧(时间切片),或者调整应用程序程序的设计以防止帧。
ProfilerMarkerProfilerMarker<TP1>ProfilerMarker<TP1, TP2>ProfilerMarker<TP1, TP2, TP3>using Unity.Profiling;public class MySystemClass{ Static 只读 ProfilerMarker<int> k_PreparePerfMarker = 新建 ProfilerMarker<int>("MySystem.Prepare", "Objects 数量"); Static 只读 ProfilerMarker<float> k_SimulatePerfMarker = 新建 ProfilerMarker<float>(ProfilerCategory.Scripts, "MySystem.模拟", "Objects Density"); public void Update(int objectsCount) { k_PreparePerfMarker.Begin(objectsCount); // ... k_PreparePerfMarker.End(); using (k_SimulatePerfMarker.Auto(objectsCount * 1.0f)) { // ... } }}
向样本添加字符串 Parameters
ProfilerMarkerProfilerMarkerExtensionusing Unity.Profiling;public class MySystemClass{ Static 只读 ProfilerMarker k_PreparePerfMarker = 新建 ProfilerMarker("MySystem.Prepare"); public void Prepare(string path) { k_PreparePerfMarker.Begin(path); // ... k_PreparePerfMarker.End(); }}