Last active
November 22, 2021 21:30
-
-
Save rfuzzo/ada2fb560516a215524ced636071633b to your computer and use it in GitHub Desktop.
Scoped Stopwatch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Runtime.CompilerServices; | |
namespace gpm.core.Util | |
{ | |
/// <summary> | |
/// A scoped stopwatch that will log the elapsed time automatically when exiting scope. | |
/// Usage: using var ssw = new ScopedStopwatch(); | |
/// </summary> | |
public sealed class ScopedStopwatch : IDisposable | |
{ | |
private readonly Stopwatch _stopwatch; | |
private readonly string _caller; | |
public ScopedStopwatch([CallerMemberName] string name = "") | |
{ | |
_caller = name; | |
_stopwatch = Stopwatch.StartNew(); | |
} | |
public void Dispose() | |
{ | |
_stopwatch.Stop(); | |
var elapsed = _stopwatch.ElapsedMilliseconds; | |
Console.WriteLine($"[{_caller}] took {elapsed.ToString()} ms."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment