Files
sbox-public/engine/Sandbox.System/Utility/FastTimer.cs
s&box team 71f266059a Open source release
This commit imports the C# engine code and game files, excluding C++ source code.

[Source-Commit: ceb3d758046e50faa6258bc3b658a30c97743268]
2025-11-24 09:05:18 +00:00

65 lines
1.8 KiB
C#

namespace Sandbox.Diagnostics;
/// <summary>
/// A lightweight, high-resolution timer for performance measurement.
/// More efficient than <see cref="Stopwatch"/> with a simpler API.
/// </summary>
/// <example>
/// var timer = FastTimer.StartNew();
/// // Do work...
/// Log.Info( $"Took {timer.ElapsedMilliSeconds}ms" );
/// </example>
public struct FastTimer
{
/// <summary>
/// Creates and starts a new FastTimer.
/// </summary>
/// <returns>A started FastTimer</returns>
public static FastTimer StartNew()
{
var ft = new FastTimer();
ft.Start();
return ft;
}
long startTimestamp;
/// <summary>
/// Starts or restarts the timer.
/// </summary>
public void Start()
{
startTimestamp = Stopwatch.GetTimestamp();
}
/// <summary>
/// Gets the timestamp when the timer was started.
/// </summary>
public readonly long StartTick => startTimestamp;
/// <summary>
/// Gets the number of ticks elapsed since the timer was started.
/// </summary>
public readonly long ElapsedTicks => (Stopwatch.GetTimestamp() - startTimestamp);
/// <summary>
/// Gets the number of microseconds elapsed since the timer was started.
/// </summary>
public readonly double ElapsedMicroSeconds => ElapsedTicks * (1_000_000.0 / Stopwatch.Frequency);
/// <summary>
/// Gets the number of milliseconds elapsed since the timer was started.
/// </summary>
public readonly double ElapsedMilliSeconds => ElapsedTicks * (1_000.0 / Stopwatch.Frequency);
/// <summary>
/// Gets the number of seconds elapsed since the timer was started.
/// </summary>
public readonly double ElapsedSeconds => ElapsedTicks * (1.0 / Stopwatch.Frequency);
/// <summary>
/// Gets the time elapsed since the timer was started as a TimeSpan.
/// </summary>
public readonly TimeSpan Elapsed => TimeSpan.FromTicks( ElapsedTicks );
}