Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@DanPuzey
Created June 9, 2014 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanPuzey/126b284a2b2dde73ae21 to your computer and use it in GitHub Desktop.
Save DanPuzey/126b284a2b2dde73ae21 to your computer and use it in GitHub Desktop.
Unity3d prefab-benchmarking component
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