Skip to content

Instantly share code, notes, and snippets.

@leandromoh
Last active March 18, 2022 13:41
Show Gist options
  • Save leandromoh/70902a2df66f5a5d183e53a3067f1236 to your computer and use it in GitHub Desktop.
Save leandromoh/70902a2df66f5a5d183e53a3067f1236 to your computer and use it in GitHub Desktop.
helper to capture how many time operations consume
class Program
{
void Foo(string[] args)
{
using var _ = this.MeasureTimeCurrentMethod();
// lot of operations
// prints "Programg.Foo was xxx ms"
}
}
public static class LogExtension
{
public static Disposable MeasureTimeCurrentMethod<T>(
this T _,
[CallerMemberName] string callerMethodName = "")
{
return new Disposable($"{typeof(T).Name}.{callerMethodName}");
}
public struct Disposable : IDisposable
{
private readonly Stopwatch _stopwatch;
private readonly string _operation;
public Disposable(string operation)
{
_operation = operation;
_stopwatch = new Stopwatch();
_stopwatch.Start();
}
public void Dispose()
{
_stopwatch.Stop();
Console.WriteLine($"{_operation} was {_stopwatch.ElapsedMilliseconds}ms");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment