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

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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值