Unity3D学习笔记(4)——获取单帧中函数耗时

来源:互联网 发布:mac磁盘不能分区 编辑:程序博客网 时间:2024/06/11 07:12

Unity3D学习笔记(4)

参考链接1
参考链接2

CheckFunctionTimeInSingleFrame.cs

namespace Assets.Scripts{    using UnityEngine;    public class CheckFunctionTimeInSingleFrame : MonoBehaviour {        // Use this for initialization        void Start () {            float t = Time.time;            TestTimeFunction();            UnityEngine.Debug.Log(string.Format("Function CostTime:{0} ms", Time.time - t));//得到结果为0,因为Time.time每帧重新赋值之后才会更新一次            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();            sw.Start(); //开始测量            TestTimeFunction();            sw.Stop();            UnityEngine.Debug.Log(string.Format("Function CostTime:{0} ms", sw.ElapsedMilliseconds)); //打印测量的时间 单位:毫秒        }        void Update()        {            //定位性能热点 这样就能在Profiler界面查看到函数的性能消耗——在Update中消耗较为直观,能在Profiler界面查看动态消耗变化            UnityEngine.Profiling.Profiler.BeginSample("TestTimeFunction");            TestTimeFunction();            UnityEngine.Profiling.Profiler.EndSample();        }        private void TestTimeFunction()        {            for (int i = 0; i < 666666; ++i)            {                //do sometihing            }        }    }}

注:

  1. 在插入性能采样代码时,特别留意函数中是否存在多个return的现象 。这些return如果没有处理好,就有可能导致性能采样的Begin和End不匹配,导致Profiler显示的结果有误。
  2. 对于协程函数,BeginSample、EndSample之间注意不能存在yeild return null ,否则可能导致Unity客户端卡死、手机卡死等现象。个人分析:Begin和End配对分析的是单帧结果,出现yeild return null代表该区间将会分两帧甚至多帧完成。
0 0
原创粉丝点击