Created
December 17, 2021 12:24
-
-
Save Epicguru/f414455d5fb7f93610077f89e6e15dbe to your computer and use it in GitHub Desktop.
A little benchmark setup to test the speed of methods in the Unity game engine.
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; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class Tester : MonoBehaviour | |
{ | |
public int Itterations = 100_000; | |
public int Runs = 20; | |
public int ObjectsToInstantiate = 1000; | |
public GameObject Prefab; | |
private Type[] componentsToAdd = new Type[] | |
{ | |
typeof(MeshFilter), | |
typeof(AudioSource), | |
typeof(BoxCollider), | |
typeof(Animator), | |
typeof(Light), | |
typeof(SphereCollider) | |
}; | |
private List<double> times = new List<double>(); | |
private int delay; | |
private int runsLeft; | |
private void Awake() | |
{ | |
foreach (var type in componentsToAdd) | |
gameObject.AddComponent(type); | |
CreateSceneObjects(); | |
delay = 30; | |
runsLeft = Runs; | |
} | |
private void CreateSceneObjects() | |
{ | |
for (int i = 0; i < ObjectsToInstantiate; i++) | |
{ | |
var go = new GameObject(UnityEngine.Random.Range(0, 10_000).ToString()); | |
for (int j = 0; j < 3; j++) | |
{ | |
var comp = componentsToAdd[UnityEngine.Random.Range(0, componentsToAdd.Length)]; | |
if (go.GetComponent(comp) != null) | |
{ | |
j--; | |
continue; | |
} | |
go.AddComponent(comp); | |
} | |
} | |
} | |
private void Update() | |
{ | |
if (runsLeft <= 0) | |
return; | |
if(delay > 0) | |
{ | |
delay--; | |
return; | |
} | |
var sw = new System.Diagnostics.Stopwatch(); | |
sw.Start(); | |
for (int i = 0; i < Itterations; i++) | |
{ | |
GetComponent<SphereCollider>(); | |
} | |
sw.Stop(); | |
double ms = sw.Elapsed.TotalMilliseconds; | |
double sec = sw.Elapsed.TotalSeconds; | |
double average = ms / Itterations; | |
double fps = 1.0 / sec; | |
times.Add(ms); | |
Debug.Log($"Total: {sw.Elapsed.TotalMilliseconds:F3} ms. Average {average} ms per call. Would result in {fps:F1} FPS."); | |
delay = UnityEngine.Random.Range(2, 20); | |
runsLeft--; | |
if (runsLeft == 0) | |
PrintSummary(); | |
} | |
private void PrintSummary() | |
{ | |
double average = 0; | |
foreach (var time in times) | |
average += time; | |
average /= times.Count; | |
double fps = 1000.0 / average; | |
double perItem = average / Itterations; | |
const double TARGET_FRAME_TIME = 1000.0 / 60; | |
double remaining = Math.Max(0, TARGET_FRAME_TIME - average); | |
Debug.Log($"[{Itterations} itterations, repeated {Runs} times] RESULTS: {average:F3} ms. Average {perItem} ms per call. Would result in {fps:F1} FPS ({remaining:F3} ms for other things)."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment