Skip to content

Instantly share code, notes, and snippets.

@ScruffyRules
Forked from MerlinVR/GlobalProfileHandler.cs
Last active February 22, 2021 12:11
Show Gist options
  • Save ScruffyRules/a031ebf0643d75d9308363c04433b77b to your computer and use it in GitHub Desktop.
Save ScruffyRules/a031ebf0643d75d9308363c04433b77b to your computer and use it in GitHub Desktop.
Basic global profiling scripts for Udon. Throw one of each script on a game object that has a TMP UI text somewhere in its children.
#define AVERAGE_OUTPUT
using UdonSharp;
using UnityEngine;
[DefaultExecutionOrder(1000000000)]
public class GlobalProfileHandler : UdonSharpBehaviour
{
public UnityEngine.UI.Text _timeText;
private GlobalProfileKickoff _kickoff;
private void Start()
{
_kickoff = GetComponent<GlobalProfileKickoff>();
}
private int _currentFrame = -1;
private float _elapsedTime = 0f;
#if AVERAGE_OUTPUT
private float _measuredTimeTotal = 0f;
private int _measuredTimeFrameCount = 0;
private const int MEASURE_FRAME_AMOUNT = 45;
#endif
private void FixedUpdate()
{
if (_currentFrame != Time.frameCount)
{
_elapsedTime = 0f;
_currentFrame = Time.frameCount;
}
if (_kickoff)
_elapsedTime += (float)_kickoff.stopwatch.Elapsed.TotalSeconds * 1000f;
}
private void Update()
{
if (_currentFrame != Time.frameCount) // FixedUpdate didn't run this frame, so reset the time
_elapsedTime = 0f;
_elapsedTime += (float)_kickoff.stopwatch.Elapsed.TotalSeconds * 1000f;
}
private void LateUpdate()
{
_elapsedTime += (float)_kickoff.stopwatch.Elapsed.TotalSeconds * 1000f;
#if AVERAGE_OUTPUT
if (_measuredTimeFrameCount >= MEASURE_FRAME_AMOUNT)
{
_timeText.text = $"{(_measuredTimeTotal / _measuredTimeFrameCount):F4}ms";
_measuredTimeTotal = 0f;
_measuredTimeFrameCount = 0;
}
_measuredTimeTotal += _elapsedTime;
_measuredTimeFrameCount += 1;
#else
_timeText.text = $"Update time:\n{_elapsedTime:F4}ms";
#endif
}
}
using UdonSharp;
using UnityEngine;
[DefaultExecutionOrder(-1000000000)]
public class GlobalProfileKickoff : UdonSharpBehaviour
{
[System.NonSerialized]
public System.Diagnostics.Stopwatch stopwatch;
private void Start()
{
stopwatch = new System.Diagnostics.Stopwatch();
}
private void FixedUpdate()
{
stopwatch.Restart();
}
private void Update()
{
stopwatch.Restart();
}
private void LateUpdate()
{
stopwatch.Restart();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment