Files
RobustToolbox/Robust.Shared/Profiling/ProfSampler.cs
Pieter-Jan Briers 41e9d9b08b Client profiling system (#2783)
Co-authored-by: metalgearsloth <comedian_vs_clown@hotmail.com>
2022-05-14 15:08:46 +10:00

59 lines
1.3 KiB
C#

using System;
using Robust.Shared.Timing;
namespace Robust.Shared.Profiling;
/// <summary>
/// Wrapper around <see cref="RStopwatch"/> that also does allocations tracking using <see cref="GC.GetAllocatedBytesForCurrentThread"/>.
/// </summary>
public struct ProfSampler
{
public RStopwatch Stopwatch;
// Same tracking rule as RStopwatch' _curTicks
private long _alloc;
public static ProfSampler StartNew()
{
ProfSampler sampler = new();
sampler.Start();
return sampler;
}
public void Start()
{
if (Stopwatch.IsRunning)
return;
Stopwatch.Start();
var startAlloc = GC.GetAllocatedBytesForCurrentThread();
_alloc = startAlloc - _alloc;
}
public void Restart()
{
Stopwatch.Restart();
_alloc = GC.GetAllocatedBytesForCurrentThread();
}
public void Stop()
{
if (!Stopwatch.IsRunning)
return;
_alloc = ElapsedAlloc;
Stopwatch.Stop();
}
public void Reset()
{
this = default;
}
public readonly long ElapsedAlloc => Stopwatch.IsRunning
? GC.GetAllocatedBytesForCurrentThread() - _alloc
: _alloc;
public readonly TimeSpan Elapsed => Stopwatch.Elapsed;
}