Skip to content

Instantly share code, notes, and snippets.

@Epicguru
Created December 17, 2021 12:24
Show Gist options
  • Select an option

  • Save Epicguru/f414455d5fb7f93610077f89e6e15dbe to your computer and use it in GitHub Desktop.

Select an option

Save Epicguru/f414455d5fb7f93610077f89e6e15dbe to your computer and use it in GitHub Desktop.

Revisions

  1. Epicguru created this gist Dec 17, 2021.
    104 changes: 104 additions & 0 deletions Tester.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,104 @@
    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).");
    }
    }