I'm interested in measuring the time it takes to execute particular methods.
I was thinking it would be really convenient to do this using a Custom Attribute instead of littering methods with code to start/stop stopwatch and sending to logger. If I could decorate the method in question using an attribute, that'd be really convenient!
I was able to create a Custom Attribute following this article: https://learn.microsoft.com/en-us/dotnet/standard/attributes/writing-custom-attributes
Like so:
public class MonitorExecutionTime : Attribute
{
private Stopwatch measureExecution;
// Start measuring on instantiation
public MonitorExecutionTime()
{
measureExecution = new Stopwatch();
measureExecution.Start();
}
// how do I hook into end invoke?
public MethodHasEnded()
{
measureExecution.Stop();
TimeSpan timeSpan = measureExecution.Elapsed;
Console.WriteLine("Time: {0}h {1}m {2}s {3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds);
}
}
But I'm not sure how to "capture" the being invoke and end invoke points of execution in order to Start the stopwatch and Stop the stopwatch (to measure the time and log it).
Has anyone took this approach in a .net core app? Thanks in advance for any pointers!