如何创建一个通用的方法定时程序?

3

我需要在应用程序的上下文中测量许多不同方法的执行时间。

当然,.NET有Stopwatch类,它允许通过其.Start()和.Stop()方法轻松计时代码段。

然而,以正常方式使用Stopwatch类需要在每个方法中添加Stopwatch对象实例和调用其.Start()和.Stop()方法。

我需要在数百种方法上使用Stopwatch功能,不想污染每个方法都加入这些代码。我也想拥有打开和关闭计时的能力。

有没有简单的方法可以在我的代码中实现通用计时解决方案?如果有,如何实现?代码分析器可以做到这一点,所以我认为这一定是可行的。


1
为什么不使用免费的分析器http://smartbear.com/products/free-tools/aqtime-standard呢? - hatchet - done with SOverflow
这个问题上的答案可能会有帮助:https://dev59.com/h3I_5IYBdhLWcg3wJfgM/ - H H
另外需要考虑的是,Stopwatch测量的是经过的时钟时间,而不是CPU时间。请参阅此链接以测量CPU时间:http://www.codeproject.com/Articles/31152/ExecutionStopwatch - hatchet - done with SOverflow
2个回答

10

仅是一个想法,可以声明一个以下的方法:

public static long Measure(Action action)
{
    Stopwatch sw = Stopwatch.StartNew();
    action();
    return sw.ElapsedMilliseconds;
}

使用作为

var duration = Measure(() => MyMethod(param1));

1
顺便说一下,前两行可以简化为 Stopwatch sw = Stopwatch.StartNew() - Eric Andres

1

您还可以研究AOP并动态创建计时方法的包装器(只适用于非静态公共方法)。

如果您使用IoC,您基本上只需要注册具有修饰符的类型,这当然可以根据需要进行自定义,并且可以关闭或甚至针对特定方法进行操作。

我以前使用过Castle:DynamicProxy来实现这一点(用于计时和错误日志记录)。

编辑:一个示例(来自旧版本的Castle:Dynamic Proxy)

TimerInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Stopwatch watch = new Stopwatch();
        watch.Start();
        invocation.Proceed();
        watch.Stop();
        //here you have the value which could be used to log (which I assume you want)
    }
}

new ProxyGenerator().CreateInterfaceProxyWithTarget<IMyInterface>(implementedObject, new TimerInterceptor());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接