Created
June 9, 2014 21:54
-
-
Save DanPuzey/126b284a2b2dde73ae21 to your computer and use it in GitHub Desktop.
Unity3d prefab-benchmarking component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using UnityEngine; | |
namespace Assets.Tools | |
{ | |
public class PrefabBenchmarker : MonoBehaviour | |
{ | |
public GameObject PrefabUnderTest; | |
public int InstancesToCreate = 1000; | |
public int FramesToTest = 100; | |
public int FramesDelayBeforeStarting = 5; | |
private float _startTime; | |
private float _instantiatePlusOneTime; | |
private float _endTime; | |
private Transform _parent; | |
private void Start() | |
{ | |
_parent = new GameObject("TestObjects").transform; | |
StartCoroutine(RunTest()); | |
} | |
private IEnumerator RunTest() | |
{ | |
// delay starting so that there's no other startup interfering | |
for (int i = 0; i < FramesDelayBeforeStarting; i++) | |
{ | |
yield return new WaitForEndOfFrame(); | |
} | |
// create the prefab instances to test | |
_startTime = Time.time; | |
CreateTestObjects(); | |
// wait to allow .Start() to run on all components | |
yield return new WaitForEndOfFrame(); | |
_instantiatePlusOneTime = Time.time; | |
// wait a number of frames for the actual benchmark | |
for (int i = 0; i < FramesToTest; i++) | |
{ | |
yield return new WaitForEndOfFrame(); | |
} | |
_endTime = Time.time; | |
// destroy the test objects in case the .Update() calls cripple the editor | |
GameObject.DestroyImmediate(_parent.gameObject); | |
LogResults(); | |
} | |
private void CreateTestObjects() | |
{ | |
for (int i = 0; i < InstancesToCreate; i++) | |
{ | |
GameObject testObject = (GameObject)GameObject.Instantiate(PrefabUnderTest); | |
testObject.transform.parent = _parent; | |
} | |
} | |
private void LogResults() | |
{ | |
var initTime = _instantiatePlusOneTime - _startTime; | |
var runTime = _endTime - _instantiatePlusOneTime; | |
var fps = FramesToTest / runTime; | |
Debug.Log(string.Format("PERFTEST: initialise {0}s; run {1}s ({2} FPS).", initTime, runTime, fps)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment