Best way to measure the execution time of methods [closed]

梦想的初衷 提交于 2020-01-01 09:59:36

问题


I'm trying to find the best way to measure the duration of a method to log them on Application Insights, I know it's 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 suppose, I don't want to write it on all the 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 it?

Thanks in advance!


回答1:


One way to do this would be to use an assembly weaver like 'Fody' with an extension that does exactly what you are looking for. Please see this link for an example extension: https://github.com/Fody/MethodTimer

How Fody works is it injects code into your code-base at compile time, utilising attributes as you have suggested in your answer. The provided extension does just as you have described using a stopwatch to log the execution time of your code.

Edit: An example of usage:

Once the library is installed, you can add the annotation [Time] to the methods you wish to measure:

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

You can then create a custom interceptor (A static class that will be automatically picked up by the Fody extension) which you case use to add a metric track into application insights:

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);
    }
}



回答2:


What I did was create an IDisposable class that would start a stopwatch in the constructor and stop/print the result in the dispose:

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 a using of 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 configurable for pieces of code.



来源:https://stackoverflow.com/questions/48705051/best-way-to-measure-the-execution-time-of-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!