-
Shortcut
-
clsStopwatchAndMemoryLogger
-
Description
-
Log Duration and Memory usage to the Console
-
Language
-
csharp
-
Types
-
Expansion
-
Author
-
Fons Sonnemans
-
Upload on
-
4-12-2025 10:20:33
-
Downloads
-
6
public sealed class StopwatchAndMemoryLogger : IDisposable {
private readonly System.Diagnostics.Stopwatch _stopwatch = new System.Diagnostics.Stopwatch();
private long _initialAllocatedBytes;
public static StopwatchAndMemoryLogger StartNew() {
var sw = new StopwatchAndMemoryLogger();
sw.Start();
return sw;
}
public void Start() {
_stopwatch.Start();
_initialAllocatedBytes = GC.GetAllocatedBytesForCurrentThread();
}
public void StopAndLog() {
if (_stopwatch.IsRunning) {
var allocatedBytes = GC.GetAllocatedBytesForCurrentThread() - _initialAllocatedBytes;
_stopwatch.Stop();
System.Console.WriteLine($$"Duration: {_stopwatch.Elapsed.TotalSeconds:N5} seconds");
System.Console.WriteLine($$"Allocated: {allocatedBytes:N0} bytes");
System.Console.WriteLine();
}
}
public void Restart() {
this.StopAndLog();
_initialAllocatedBytes = GC.GetAllocatedBytesForCurrentThread();
_stopwatch.Restart();
}
public void Dispose() => this.StopAndLog();
}