Unity3D--使用Profiler精确定位性能热点的优化技巧

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq826364410/article/details/81292973

       在使用Profiler定位代码的性能热点时,我们很多时候往往忽略Profiler的提供接口,当发现某个Update函数特别耗时时,没有有效的手段进一步定位热点出自该Update函数的哪一个模块或哪一段代码。 

       使用Profiler评估客户端性能时,推荐使用Profiler提供的性能采样接口,来更精确地分析定位客户端存在的性能问题。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Profiling;

public class TestProfiler : MonoBehaviour
{
    int t = 10000;

    // 每帧Update都会进行校验和运行
    void Update()
    {
        Check(t); // 校验
        Run(); // 运行
    }

    void Check(int n)
    {
        Profiler.BeginSample("Check");
        CheckA(); // 校验模块A

        Profiler.BeginSample("Calculate b");
        // 数值运算
        int b = n - 100;
        if (b < 10)
            b = 10;
        Profiler.EndSample();

        CheckB(b); // 校验模块B
        Profiler.EndSample();
    }

    void CheckA()
    {
        Profiler.BeginSample("CheckA");
        Debug.Log("校验模块A");
        Profiler.EndSample();
    }

    void CheckB(int loopCount)
    {
        Profiler.BeginSample("CheckB");
        Debug.Log("校验模块B");

        Profiler.BeginSample("new List<string>");
        List<string> strList = new List<string>();
        Profiler.EndSample();

        for (int i = 0; i < loopCount; ++i)
        {
            Profiler.BeginSample("Add str to list");
            string str = string.Format("CheckB:{0}", i);
            strList.Add(str);
            Profiler.EndSample();
        }

        Debug.Log(string.Format("list count: {0}", strList.Count));
        Profiler.EndSample();
    }

    void Run()
    {
        Profiler.BeginSample("Run");
        Debug.Log("开始运行");
        DoSomething();
        Profiler.EndSample();
    }

    void DoSomething()
    {
    }

}

猜你喜欢

转载自blog.csdn.net/qq826364410/article/details/81292973
今日推荐