unity3d:函数耗时记录,Profiler性能采样

2023-08-24 15:20:03 浏览数 (1)

Time.time

在一帧内,Time.time只会赋值更新一次,所以一帧内获取不到时间差值。

代码语言:javascript复制
void Start () {
        TestArrayAList();
    }

    void TestArrayAList()
    {
        int max = 100000000;
        int[] array;
        array = new int[max];
        List<int> list = new List<int>();
        float time = Time.time;

        for (int i = 0; i < max; i  )
        {
            array[i] = i;
        }
        Debug.Log(Time.time - time);

        time = Time.time;
        for (int i = 0; i < max; i  )
        {
            list.Add(i);
        }
        Debug.Log(Time.time - time);
        array = null;
    }

如上代码,输出为0

Stopwatch

代码语言:javascript复制
void TestArrayAList()
    {
        int max = 100000000;
        int[] array;
        array = new int[max];
        List<int> list = new List<int>();
        float time = Time.time;
        Stopwatch stop = new Stopwatch();
        stop.Start();
        for (int i = 0; i < max; i  )
        {
            array[i] = i;
        }
        UnityEngine.Debug.Log(stop.ElapsedMilliseconds);
        stop.Reset();
        stop.Start();
        time = Time.time;
        for (int i = 0; i < max; i  )
        {
            list.Add(i);
        }
        UnityEngine.Debug.Log(stop.ElapsedMilliseconds);
        array = null;
    }

Profiler性能采样

代码语言:javascript复制
void TestArrayAList()
    {
        int max = 10000; 
        int[] array;
        array = new int[max];
        List<int> list = new List<int>();
        float time = Time.time;
        Stopwatch stop = new Stopwatch();
        stop.Start();
        Profiler.BeginSample("TestArray");
        for (int i = 0; i < max; i  ) 
        {
            array[i] = i;
        }
        Profiler.EndSample();
        UnityEngine.Debug.Log(stop.ElapsedMilliseconds);
        stop.Reset();
        stop.Start();
        time = Time.time;
        Profiler.BeginSample("TestList");
        for (int i = 0; i < max; i  )
        {
            list.Add(i);
        }
        Profiler.EndSample();
        UnityEngine.Debug.Log(stop.ElapsedMilliseconds);
        array = null;
    }

    // Update is called once per frame
    void Update () {
        TestArrayAList();

    }

0 人点赞