Best way to measure runtime methods

I'm trying to find a better way to measure the duration of a method for registering them in Application Insights, I know what is possible if we do something like this:

public void TestMethod() { var sw = Stopwatch.StartNew(); //code here sw.Stop(); Console.WriteLine("Time elapsed: {0}", sw.Elapsed); } 

But, as you believe, I do not want to write it on all methods, ideally, I want to use a decorator, something similar to this.

 [MeasureTime] public void TestMethod() { //code here } 

Or something similar. So my question is: how can I build something like this? Is there a better way to do this?

Thanks in advance!

+5
source share
2 answers

One way to do this is to use a linker, such as "Fody," with an extension that does exactly what you are looking for. See this link for an example extension: https://github.com/Fody/MethodTimer

How Fody works, it injects code into its codebase at compile time, using attributes, as you suggested in your answer. The provided extension works the same as you described, using a stopwatch to record the execution time of your code.

Edit: usage example:

After installing the library, you can add the [Time] annotation to the methods that you want to measure:

 [Time] public void TestMethod() { //code here } 

Then you can create a custom interceptor (a static class that will be automatically loaded by the Fody extension) that you use to add a metric track to application information:

 public static class MethodTimeLogger { public static void Log(MethodBase methodBase, long milliseconds) { var sample = new MetricTelemetry(); sample.Name = methodBase.Name; sample.Value = milliseconds; // Your telemetryClient here telemetryClient.TrackMetric(sample); } } 
+6
source

I created an IDisposable class that would start the stopwatch in the constructor and stop / print the result at the disposal:

 public class Superwatch : IDisposable { static Stopwatch Watch = new Stopwatch(); static Superwatch() { Watch.Start(); } TimeSpan Start; public Superwatch() { Start = Watch.Elapsed; } public void Dispose() { TimeSpan elapsed = Watch.Elapsed - Start; Console.WriteLine($"Time elapsed: {elapsed}"); } } 

Then just pack the method into an instance of the class you created.

 using (var watch = new Superwatch()) { //piece of code } 

Not as clean as a decorator, but relatively clean imo and customizable for code snippets.

0
source

Source: https://habr.com/ru/post/1275260/


All Articles