衡量方法执行时间的最佳方法 [英] Best way to measure the execution time of methods

查看:83
本文介绍了衡量方法执行时间的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到最佳方法来衡量将其记录在Application Insights上的方法的持续时间,我知道我们可以执行以下操作:

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?

提前谢谢!

推荐答案

做到这一点的一种方法是使用像'Fody'这样的程序集编织器,其扩展名完全可以满足您的需求.请参见此链接以获取示例扩展: https://github.com/Fody/MethodTimer

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

Fody的工作方式是在编译时利用您在答案中建议的属性将代码注入代码库中.所提供的扩展名与使用秒表记录代码的执行时间一样.

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.

用法示例:

一旦安装了库,就可以将[时间]注释添加到要测量的方法中:

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

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

然后,您可以创建一个自定义的拦截器(一个静态类,该类将由Fody扩展程序自动拾取),您可以使用该拦截器将度量标准跟踪添加到应用程序见解中:

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

这篇关于衡量方法执行时间的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆