Skip to content

Instantly share code, notes, and snippets.

@rfuzzo
Last active November 22, 2021 21:30
Show Gist options
  • Save rfuzzo/ada2fb560516a215524ced636071633b to your computer and use it in GitHub Desktop.
Save rfuzzo/ada2fb560516a215524ced636071633b to your computer and use it in GitHub Desktop.
Scoped Stopwatch
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