Unity中計算某一個方法的耗時的幾種方法
阿新 • • 發佈:2019-01-30
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圖