Unity中计算某一个方法的耗时的几种方法

1、Time.time

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

2、Stopwatch

实例可以测量一个时间间隔的运行时间,也可以测量多个时间间隔的总运行时间。调用Start方法时,开始累积运行时间计数;调用Stop方法时,结束当前时间间隔测量,并冻结累积运行时间值;调用Reset方法可以清除现有实例中的累积运行时间。通过属性Elapsed、ElapsedMilliseconds、ElapsedTicks查询运行时间值。

3、Profiler

打开Profiler界面,使用Profiler.BeginSample和Profiler.EndSample查看一帧运行时间。

4、源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using UnityEngine;
using System.Collections;
using System.Diagnostics;
using UnityEngine.Profiling;
 
public class NewBehaviourScript : MonoBehaviour
{
 
    void Start()
    {
 
        float t = Time.time;
        TestMethod();
        UnityEngine.Debug.Log(string.Format("total: {0} ms", Time.time - t));
 
        Stopwatch sw = new Stopwatch();
        sw.Start();
        TestMethod();
        sw.Stop();
        UnityEngine.Debug.Log(string.Format("total: {0} ms", sw.ElapsedMilliseconds));
 
 
        Profiler.BeginSample("TestMethod");
        TestMethod();
        Profiler.EndSample();
    }
 
 
    void TestMethod()
    {
        for (int i = 0; i < 10000000; i++)
        {
        }
    }
 
}

4、Profile图

Unity中计算某一个方法的耗时的几种方法