Last active
March 18, 2022 13:41
-
-
Save leandromoh/70902a2df66f5a5d183e53a3067f1236 to your computer and use it in GitHub Desktop.
helper to capture how many time operations consume
This file contains hidden or 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
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