diff --git a/org.mixedrealitytoolkit.diagnostics/AssemblyInfo.cs b/org.mixedrealitytoolkit.diagnostics/AssemblyInfo.cs index 4043f74c4..62d45e9d4 100644 --- a/org.mixedrealitytoolkit.diagnostics/AssemblyInfo.cs +++ b/org.mixedrealitytoolkit.diagnostics/AssemblyInfo.cs @@ -2,10 +2,13 @@ // Licensed under the BSD 3-Clause using System.Reflection; +using System.Runtime.CompilerServices; [assembly: AssemblyProduct("Mixed Reality Toolkit Diagnostic Tools")] [assembly: AssemblyCopyright("Copyright (c) Mixed Reality Toolkit Contributors")] +[assembly: InternalsVisibleTo("MixedReality.Toolkit.Diagnostics.Runtime.Tests")] + // The AssemblyVersion attribute is checked-in and is recommended not to be changed often. // https://docs.microsoft.com/troubleshoot/visualstudio/general/assembly-version-assembly-file-version // AssemblyFileVersion and AssemblyInformationalVersion are added by pack-upm.ps1 to match the current MRTK build version. diff --git a/org.mixedrealitytoolkit.diagnostics/CHANGELOG.md b/org.mixedrealitytoolkit.diagnostics/CHANGELOG.md index 067563146..814e1959f 100644 --- a/org.mixedrealitytoolkit.diagnostics/CHANGELOG.md +++ b/org.mixedrealitytoolkit.diagnostics/CHANGELOG.md @@ -2,6 +2,21 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## Unreleased + +### Added + +* Added runtime test suite (`SimpleProfilerTests`) verifying null-safety, numeric formatting accuracy, and Zero-GC compliance across Diagnostics profiler and subsystem hot paths. [PR #1149](https://github.com/MixedRealityToolkit/MixedRealityToolkit-Unity/pull/1149) + +### Fixed + +* Fixed `NullReferenceException` in `SimpleProfiler` when any `TMP_Text` serialized fields are left unassigned. [PR #1149](https://github.com/MixedRealityToolkit/MixedRealityToolkit-Unity/pull/1149) +* Guarded against division by zero in `MRTKPerformanceStatsSubsystem.UpdateFrameRate` using `MathUtilities.ZeroTolerance` and simplified the frame rate calculation. [PR #1149](https://github.com/MixedRealityToolkit/MixedRealityToolkit-Unity/pull/1149) + +### Changed + +* Eliminated per-frame string allocations in `SimpleProfiler.FixedUpdate` by leveraging `TMP_Text.SetText` native float formatting, reusable `StringBuilder` buffer with zero-allocating integer/fraction formatter, and delta caching to skip updates when stats are unchanged. [PR #1149](https://github.com/MixedRealityToolkit/MixedRealityToolkit-Unity/pull/1149) + ## [3.0.3] - 2025-11-12 ### Fixed diff --git a/org.mixedrealitytoolkit.diagnostics/Subsystems/MRTKSubsystems/MRTKPerformanceStatsSubsystem.cs b/org.mixedrealitytoolkit.diagnostics/Subsystems/MRTKSubsystems/MRTKPerformanceStatsSubsystem.cs index a7af94fe3..cd3075271 100644 --- a/org.mixedrealitytoolkit.diagnostics/Subsystems/MRTKSubsystems/MRTKPerformanceStatsSubsystem.cs +++ b/org.mixedrealitytoolkit.diagnostics/Subsystems/MRTKSubsystems/MRTKPerformanceStatsSubsystem.cs @@ -114,7 +114,7 @@ protected virtual void UpdateFrameRate() if (elapsedTime >= samplePeriod) { // Calculate the frame rate. - FrameRate = 1f / (elapsedTime / frameCount); + FrameRate = elapsedTime > MathUtilities.ZeroTolerance ? (float)frameCount / elapsedTime : 0f; // Reset state for the next sampling. frameCount = 0; diff --git a/org.mixedrealitytoolkit.diagnostics/Tests/Editor/AssemblyInfo.cs b/org.mixedrealitytoolkit.diagnostics/Tests/Editor/AssemblyInfo.cs index 8ac8aabc5..6484d6263 100644 --- a/org.mixedrealitytoolkit.diagnostics/Tests/Editor/AssemblyInfo.cs +++ b/org.mixedrealitytoolkit.diagnostics/Tests/Editor/AssemblyInfo.cs @@ -3,7 +3,7 @@ using System.Reflection; -[assembly: AssemblyProduct("Mixed Reality Toolkit Performance Editor Tests")] +[assembly: AssemblyProduct("Mixed Reality Toolkit Diagnostics Editor Tests")] [assembly: AssemblyCopyright("Copyright (c) Mixed Reality Toolkit Contributors")] // The AssemblyVersion attribute is checked-in and is recommended not to be changed often. diff --git a/org.mixedrealitytoolkit.diagnostics/Tests/Editor/SmokeTest.cs b/org.mixedrealitytoolkit.diagnostics/Tests/Editor/SmokeTest.cs index 1cf6d6ca3..27b86211b 100644 --- a/org.mixedrealitytoolkit.diagnostics/Tests/Editor/SmokeTest.cs +++ b/org.mixedrealitytoolkit.diagnostics/Tests/Editor/SmokeTest.cs @@ -6,12 +6,12 @@ using NUnit.Framework; -namespace MixedReality.Toolkit.Performance.Tests.EditMode +namespace MixedReality.Toolkit.Diagnostics.Tests.EditMode { internal class SmokeTest { [Test] - public void PerformancePackageTest() + public void DiagnosticsPackageTest() { Assert.IsTrue(true); } diff --git a/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/AssemblyInfo.cs b/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/AssemblyInfo.cs index c531d9e2d..49bf897e4 100644 --- a/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/AssemblyInfo.cs +++ b/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/AssemblyInfo.cs @@ -3,7 +3,7 @@ using System.Reflection; -[assembly: AssemblyProduct("Mixed Reality Toolkit Performance Runtime Tests")] +[assembly: AssemblyProduct("Mixed Reality Toolkit Diagnostics Runtime Tests")] [assembly: AssemblyCopyright("Copyright (c) Mixed Reality Toolkit Contributors")] // The AssemblyVersion attribute is checked-in and is recommended not to be changed often. diff --git a/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/MRTK.Diagnostics.RuntimeTests.asmdef b/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/MRTK.Diagnostics.RuntimeTests.asmdef index 98483447b..c1ae1f4c9 100644 --- a/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/MRTK.Diagnostics.RuntimeTests.asmdef +++ b/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/MRTK.Diagnostics.RuntimeTests.asmdef @@ -2,7 +2,11 @@ "name": "MixedReality.Toolkit.Diagnostics.Runtime.Tests", "rootNamespace": "", "references": [ + "MixedReality.Toolkit.Core", + "MixedReality.Toolkit.Core.TestUtilities", "MixedReality.Toolkit.Diagnostics", + "MixedReality.Toolkit.Diagnostics.Visualization", + "Unity.TextMeshPro", "UnityEditor.TestRunner", "UnityEngine.TestRunner" ], diff --git a/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/SimpleProfilerTests.cs b/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/SimpleProfilerTests.cs new file mode 100644 index 000000000..dfc805786 --- /dev/null +++ b/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/SimpleProfilerTests.cs @@ -0,0 +1,280 @@ +// Copyright (c) Mixed Reality Toolkit Contributors +// Licensed under the BSD 3-Clause + +// Disable "missing XML comment" warning for tests. While nice to have, this documentation is not required. +#pragma warning disable CS1591 + +using MixedReality.Toolkit; +using MixedReality.Toolkit.Core.Tests; +using MixedReality.Toolkit.Diagnostics; +using MixedReality.Toolkit.Subsystems; +using NUnit.Framework; +using System; +using System.Collections; +using System.Diagnostics; +using TMPro; +using UnityEngine; +using UnityEngine.TestTools; +using UnityEngine.TestTools.Constraints; +using Debug = UnityEngine.Debug; +using Is = UnityEngine.TestTools.Constraints.Is; +using Object = UnityEngine.Object; + +namespace MixedReality.Toolkit.Diagnostics.Tests +{ + /// + /// Runtime test suite verifying null-safety, numeric formatting accuracy, + /// and Zero-GC invariants across the SimpleProfiler visualizer and diagnostics subsystem hot paths. + /// + public class SimpleProfilerTests : BaseRuntimeTests + { + private PerformanceStatsSubsystem subsystem; + + [UnitySetUp] + public override IEnumerator Setup() + { + yield return base.Setup(); + subsystem = SubsystemTestUtilities.CreateAndEnsureExists(); + subsystem.Start(); + } + + [UnityTearDown] + public override IEnumerator TearDown() + { + if (subsystem != null) + { + if (subsystem.running) + { + subsystem.Stop(); + } + subsystem.Destroy(); + subsystem = null; + } + yield return base.TearDown(); + } + + [UnityTest] + public IEnumerator SimpleProfiler_NullReferences_DoesNotThrow() + { + GameObject go = new GameObject("NullProfilerHolder"); + SimpleProfiler profiler = go.AddComponent(); + + // All TMP_Text references are unassigned (null) by default. + // With the subsystem running, UpdateCounters exercises the null checks on all text fields. + Assert.DoesNotThrow(() => + { + profiler.UpdateCounters(); + }, "SimpleProfiler.UpdateCounters must gracefully handle unassigned TMP_Text fields without throwing NullReferenceException."); + + // Let Unity's player loop execute Start() and FixedUpdate() naturally + yield return null; + + Assert.DoesNotThrow(() => + { + profiler.UpdateCounters(); + }, "SimpleProfiler.UpdateCounters must gracefully handle null fields on subsequent updates."); + + Object.Destroy(go); + yield return null; + } + + [UnityTest] + public IEnumerator SimpleProfiler_FixedUpdate_AllocatesZeroGC() + { + // Ensure subsystem memory statistics are populated + ((IMRTKManagedSubsystem)subsystem).FixedUpdate(); + ((IMRTKManagedSubsystem)subsystem).LateUpdate(); + + GameObject root = new GameObject("ProfilerTestRoot"); + SimpleProfiler profiler = root.AddComponent(); + + // Set up TextMeshPro components + GameObject goRamLimit = new GameObject("RamLimit"); + goRamLimit.transform.SetParent(root.transform); + TMP_Text tmpRamLimit = goRamLimit.AddComponent(); + + GameObject goAllocRam = new GameObject("AllocatedRam"); + goAllocRam.transform.SetParent(root.transform); + TMP_Text tmpAllocRam = goAllocRam.AddComponent(); + + GameObject goPeakRam = new GameObject("PeakRam"); + goPeakRam.transform.SetParent(root.transform); + TMP_Text tmpPeakRam = goPeakRam.AddComponent(); + + GameObject goFps = new GameObject("FrameRate"); + goFps.transform.SetParent(root.transform); + TMP_Text tmpFps = goFps.AddComponent(); + + GameObject goHz = new GameObject("RefreshRate"); + goHz.transform.SetParent(root.transform); + TMP_Text tmpHz = goHz.AddComponent(); + + profiler.RamLimit = tmpRamLimit; + profiler.AllocatedRam = tmpAllocRam; + profiler.PeakAllocatedRam = tmpPeakRam; + profiler.FrameRate = tmpFps; + profiler.RefreshRate = tmpHz; + + yield return null; + + // Warmup: initial tick where lastBytes != currentBytes, populating all strings + profiler.UpdateCounters(); + + // Verify initial values were formatted and populated from the running subsystem + Assert.AreNotEqual("--", tmpRamLimit.text); + Assert.AreNotEqual("--", tmpAllocRam.text); + Assert.AreNotEqual("--", tmpPeakRam.text); + + // Benchmark execution time across hot-path frames + const int iterations = 1000; + Stopwatch sw = Stopwatch.StartNew(); + for (int i = 0; i < iterations; i++) + { + profiler.UpdateCounters(); + } + sw.Stop(); + double usPerCall = (sw.Elapsed.TotalMilliseconds * 1000.0) / iterations; + Debug.Log($"[Profiler Perf] SimpleProfiler.UpdateCounters: {usPerCall:F2} µs/call across {iterations} iterations."); + + // Zero-GC assertion on the per-frame hot path + Assert.That(() => + { + for (int i = 0; i < 50; i++) + { + profiler.UpdateCounters(); + } + }, Is.Not.AllocatingGCMemory(), "SimpleProfiler.UpdateCounters must not allocate managed heap memory on the per-frame hot path."); + + Object.Destroy(root); + yield return null; + } + + [UnityTest] + public IEnumerator SimpleProfiler_TextOutput_AccurateFormatting() + { + // Populate subsystem stats + ((IMRTKManagedSubsystem)subsystem).FixedUpdate(); + yield return new WaitForSeconds(0.12f); + ((IMRTKManagedSubsystem)subsystem).LateUpdate(); + + GameObject root = new GameObject("ProfilerFormattingRoot"); + SimpleProfiler profiler = root.AddComponent(); + + GameObject goRamLimit = new GameObject("RamLimit"); + goRamLimit.transform.SetParent(root.transform); + TMP_Text tmpRamLimit = goRamLimit.AddComponent(); + + GameObject goAllocRam = new GameObject("AllocatedRam"); + goAllocRam.transform.SetParent(root.transform); + TMP_Text tmpAllocRam = goAllocRam.AddComponent(); + + GameObject goPeakRam = new GameObject("PeakRam"); + goPeakRam.transform.SetParent(root.transform); + TMP_Text tmpPeakRam = goPeakRam.AddComponent(); + + GameObject goFps = new GameObject("FrameRate"); + goFps.transform.SetParent(root.transform); + TMP_Text tmpFps = goFps.AddComponent(); + + GameObject goHz = new GameObject("RefreshRate"); + goHz.transform.SetParent(root.transform); + TMP_Text tmpHz = goHz.AddComponent(); + + profiler.RamLimit = tmpRamLimit; + profiler.AllocatedRam = tmpAllocRam; + profiler.PeakAllocatedRam = tmpPeakRam; + profiler.FrameRate = tmpFps; + profiler.RefreshRate = tmpHz; + + yield return null; + + // SimpleProfiler.FixedUpdate() executes naturally, updating all counters via UpdateCounters(). + // RAM strings must match format: " ()" + StringAssert.IsMatch(@"^\d+ \(\d+\.\d{2}\)$", tmpRamLimit.text); + StringAssert.IsMatch(@"^\d+ \(\d+\.\d{2}\)$", tmpAllocRam.text); + StringAssert.IsMatch(@"^\d+ \(\d+\.\d{2}\)$", tmpPeakRam.text); + + // Frame rate must match format: "" + StringAssert.IsMatch(@"^\d+\.\d{2}$", tmpFps.text); + + // Refresh rate remains "--" when no XRDisplaySubsystem is active in playmode test scene + Assert.AreEqual("--", tmpHz.text); + + Object.Destroy(root); + yield return null; + } + + [UnityTest] + public IEnumerator PerformanceStats_ZeroDivisionSafety() + { + // Verify MRTKPerformanceStatsSubsystem computes valid and finite stats without division by zero. + // 1. Initial state before sampling period: FrameRate is safe (0, non-infinite, non-NaN) + Assert.AreEqual(0f, subsystem.FrameRate); + Assert.IsFalse(float.IsInfinity(subsystem.FrameRate)); + Assert.IsFalse(float.IsNaN(subsystem.FrameRate)); + + // 2. Memory status tracking + ((IMRTKManagedSubsystem)subsystem).FixedUpdate(); + Assert.Greater(subsystem.RamLimit, 0UL, "RamLimit must be greater than 0."); + Assert.Greater(subsystem.AllocatedRam, 0UL, "AllocatedRam must be greater than 0."); + Assert.GreaterOrEqual(subsystem.PeakAllocatedRam, subsystem.AllocatedRam, "PeakAllocatedRam must be >= AllocatedRam."); + + // 3. Tick LateUpdate immediately (elapsed time < samplePeriod) - must remain safe + ((IMRTKManagedSubsystem)subsystem).LateUpdate(); + Assert.AreEqual(0f, subsystem.FrameRate); + Assert.IsFalse(float.IsInfinity(subsystem.FrameRate)); + Assert.IsFalse(float.IsNaN(subsystem.FrameRate)); + + // 4. Wait past the sample period (samplePeriod = 0.1s) + yield return new WaitForSeconds(0.15f); + ((IMRTKManagedSubsystem)subsystem).LateUpdate(); + + // FrameRate must now be calculated, positive, finite, and not NaN + Assert.Greater(subsystem.FrameRate, 0f, "FrameRate should be positive after sample period elapses."); + Assert.IsFalse(float.IsInfinity(subsystem.FrameRate), "FrameRate must not be Infinity."); + Assert.IsFalse(float.IsNaN(subsystem.FrameRate), "FrameRate must not be NaN."); + } + + [Test] + public void SimpleProfiler_FormatRamString_ZeroGC() + { + GameObject go = new GameObject("FormatRamTest"); + SimpleProfiler profiler = go.AddComponent(); + System.Text.StringBuilder sb = new System.Text.StringBuilder(64); + + // 1. Boundary value 0 + profiler.FormatRamString(sb, 0UL, 0.0f); + Assert.AreEqual("0 (0.00)", sb.ToString()); + + // 2. Megabyte boundary (1 MB) + sb.Clear(); + profiler.FormatRamString(sb, 1048576UL, 1.0f); + Assert.AreEqual("1048576 (1.00)", sb.ToString()); + + // 3. Fractional rounding + sb.Clear(); + profiler.FormatRamString(sb, 2097152UL, 2.50f); + Assert.AreEqual("2097152 (2.50)", sb.ToString()); + + // 4. Large RAM (e.g. 16 GB) + sb.Clear(); + profiler.FormatRamString(sb, 17179869184UL, 16384.0f); + Assert.AreEqual("17179869184 (16384.00)", sb.ToString()); + + // 5. Zero-GC Assertion + TestDelegate formatDelegate = () => + { + for (int i = 0; i < 50; i++) + { + sb.Clear(); + profiler.FormatRamString(sb, 17179869184UL, 16384.0f); + } + }; + formatDelegate(); + Assert.That(formatDelegate, Is.Not.AllocatingGCMemory(), "FormatRamString must not allocate any managed heap memory."); + + Object.Destroy(go); + } + } +} +#pragma warning restore CS1591 diff --git a/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/SimpleProfilerTests.cs.meta b/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/SimpleProfilerTests.cs.meta new file mode 100644 index 000000000..ee9b8f224 --- /dev/null +++ b/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/SimpleProfilerTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 88f0cdb1e114e664ea6e21af328fc8fd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/SmokeTest.cs b/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/SmokeTest.cs index 091659a1f..9ebaa19da 100644 --- a/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/SmokeTest.cs +++ b/org.mixedrealitytoolkit.diagnostics/Tests/Runtime/SmokeTest.cs @@ -7,12 +7,12 @@ using System.Collections; using UnityEngine.TestTools; -namespace MixedReality.Toolkit.Performance.Tests +namespace MixedReality.Toolkit.Diagnostics.Tests { internal class SmokeTest { [UnityTest] - public IEnumerator PerformancePackageTest() + public IEnumerator DiagnosticsPackageTest() { yield return null; } diff --git a/org.mixedrealitytoolkit.diagnostics/Visualizers/AssemblyInfo.cs b/org.mixedrealitytoolkit.diagnostics/Visualizers/AssemblyInfo.cs index 1dc51469e..3743c7014 100644 --- a/org.mixedrealitytoolkit.diagnostics/Visualizers/AssemblyInfo.cs +++ b/org.mixedrealitytoolkit.diagnostics/Visualizers/AssemblyInfo.cs @@ -2,10 +2,13 @@ // Licensed under the BSD 3-Clause using System.Reflection; +using System.Runtime.CompilerServices; [assembly: AssemblyProduct("Mixed Reality Toolkit Diagnostics Visualization")] [assembly: AssemblyCopyright("Copyright (c) Mixed Reality Toolkit Contributors")] +[assembly: InternalsVisibleTo("MixedReality.Toolkit.Diagnostics.Runtime.Tests")] + // The AssemblyVersion attribute is checked-in and is recommended not to be changed often. // https://docs.microsoft.com/troubleshoot/visualstudio/general/assembly-version-assembly-file-version // AssemblyFileVersion and AssemblyInformationalVersion are added by pack-upm.ps1 to match the current MRTK build version. diff --git a/org.mixedrealitytoolkit.diagnostics/Visualizers/SimpleProfiler.cs b/org.mixedrealitytoolkit.diagnostics/Visualizers/SimpleProfiler.cs index 57b520f00..972477966 100644 --- a/org.mixedrealitytoolkit.diagnostics/Visualizers/SimpleProfiler.cs +++ b/org.mixedrealitytoolkit.diagnostics/Visualizers/SimpleProfiler.cs @@ -1,6 +1,8 @@ // Copyright (c) Mixed Reality Toolkit Contributors // Licensed under the BSD 3-Clause +using System; +using System.Text; using TMPro; using UnityEngine; @@ -88,45 +90,154 @@ public TMP_Text PeakAllocatedRam private const string noData = "--"; + private readonly StringBuilder stringBuilder = new StringBuilder(64); + private readonly char[] digitBuffer = new char[32]; + + private ulong lastRamLimit = ulong.MaxValue; + private ulong lastAllocatedRam = ulong.MaxValue; + private ulong lastPeakAllocatedRam = ulong.MaxValue; + private float lastFrameRate = -1f; + private float lastRefreshRate = -1f; + /// /// A Unity event function that is called on the frame when a script is enabled just before any of the update methods are called the first time. /// private void Start() { - RamLimit.text = noData; - AllocatedRam.text = noData; - PeakAllocatedRam.text = noData; + if (RamLimit != null) + { + RamLimit.text = noData; + } + if (AllocatedRam != null) + { + AllocatedRam.text = noData; + } + if (PeakAllocatedRam != null) + { + PeakAllocatedRam.text = noData; + } - FrameRate.text = noData; - RefreshRate.text = noData; + if (FrameRate != null) + { + FrameRate.text = noData; + } + if (RefreshRate != null) + { + RefreshRate.text = noData; + } } /// /// A Unity event function that is called at an framerate independent frequency, and is only called if this object is enabled. /// private void FixedUpdate() + { + UpdateCounters(); + } + + /// + /// Formats and updates the visualizer text counters. + /// + internal void UpdateCounters() { if (PerformanceStatsHelpers.Subsystem != null) { - ulong limitBytes = PerformanceStatsHelpers.Subsystem.RamLimit; - float limitMegabytes = MathUtilities.BytesToMegabytes(limitBytes); - RamLimit.text = $"{limitBytes} ({limitMegabytes:0.00})"; + UpdateRamText(RamLimit, ref lastRamLimit, PerformanceStatsHelpers.Subsystem.RamLimit); + UpdateRamText(AllocatedRam, ref lastAllocatedRam, PerformanceStatsHelpers.Subsystem.AllocatedRam); + UpdateRamText(PeakAllocatedRam, ref lastPeakAllocatedRam, PerformanceStatsHelpers.Subsystem.PeakAllocatedRam); + + if (FrameRate != null) + { + float fps = PerformanceStatsHelpers.Subsystem.FrameRate; + if (Mathf.Abs(fps - lastFrameRate) > MathUtilities.ZeroTolerance) + { + lastFrameRate = fps; + FrameRate.SetText("{0:0.00}", fps); + } + } + } + + if (RefreshRate != null) + { + float refRate = -1f; + bool? haveRefreshRate = XRSubsystemHelpers.DisplaySubsystem?.TryGetDisplayRefreshRate(out refRate); + if (haveRefreshRate.HasValue && haveRefreshRate.Value) + { + if (Mathf.Abs(refRate - lastRefreshRate) > MathUtilities.ZeroTolerance) + { + lastRefreshRate = refRate; + RefreshRate.SetText("{0:0.00}", refRate); + } + } + else if (lastRefreshRate >= 0f || RefreshRate.text != noData) + { + lastRefreshRate = -1f; + RefreshRate.text = noData; + } + } + } + + private void UpdateRamText(TMP_Text textComponent, ref ulong lastBytes, ulong currentBytes) + { + if (textComponent == null) + { + return; + } + + if (currentBytes != lastBytes) + { + lastBytes = currentBytes; + float megabytes = MathUtilities.BytesToMegabytes(currentBytes); + stringBuilder.Clear(); + FormatRamString(stringBuilder, currentBytes, megabytes); + textComponent.SetText(stringBuilder); + } + } + + internal void FormatRamString(StringBuilder sb, ulong bytes, float megabytes) + { + AppendULong(sb, bytes); + sb.Append(" ("); + AppendFixed2(sb, megabytes); + sb.Append(')'); + } - ulong allocatedBytes = PerformanceStatsHelpers.Subsystem.AllocatedRam; - float allocatedMegabytes = MathUtilities.BytesToMegabytes(allocatedBytes); - AllocatedRam.text = $"{allocatedBytes} ({allocatedMegabytes:0.00})"; + private void AppendULong(StringBuilder sb, ulong value) + { + if (value == 0) + { + sb.Append('0'); + return; + } - ulong peakBytes = PerformanceStatsHelpers.Subsystem.PeakAllocatedRam; - float peakMegabytes = MathUtilities.BytesToMegabytes(peakBytes); - PeakAllocatedRam.text = $"{peakBytes} ({peakMegabytes:0.00})"; + int startIndex = digitBuffer.Length; + while (value > 0) + { + digitBuffer[--startIndex] = (char)('0' + (value % 10)); + value /= 10; + } + for (int i = startIndex; i < digitBuffer.Length; i++) + { + sb.Append(digitBuffer[i]); + } + } - FrameRate.text = PerformanceStatsHelpers.Subsystem.FrameRate.ToString("0.00"); + private void AppendFixed2(StringBuilder sb, float value) + { + if (value < 0f) + { + sb.Append('-'); + value = -value; } - float refRate = -1f; - bool? haveRefreshRate = XRSubsystemHelpers.DisplaySubsystem?.TryGetDisplayRefreshRate(out refRate); - RefreshRate.text = (haveRefreshRate.HasValue && haveRefreshRate.Value) ? - refRate.ToString("0.00") : noData; + ulong totalHundredths = (ulong)(value * 100f + 0.5f); + ulong whole = totalHundredths / 100UL; + ulong fraction = totalHundredths % 100UL; + + AppendULong(sb, whole); + sb.Append('.'); + sb.Append((char)('0' + (fraction / 10))); + sb.Append((char)('0' + (fraction % 10))); } } } diff --git a/org.mixedrealitytoolkit.diagnostics/package.json b/org.mixedrealitytoolkit.diagnostics/package.json index 3d12bff44..d8bacf1a8 100644 --- a/org.mixedrealitytoolkit.diagnostics/package.json +++ b/org.mixedrealitytoolkit.diagnostics/package.json @@ -1,6 +1,6 @@ { "name": "org.mixedrealitytoolkit.diagnostics", - "version": "3.0.3-development", + "version": "3.0.4-development", "description": "Subsystems and utilities for common diagnostic and performance monitoring tasks.", "displayName": "MRTK Diagnostics", "msftFeatureCategory": "MRTK3",