如何为时间方法创建通用例程?

时间:2012-09-13 18:49:32

标签: c# .net

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

.NET当然有Stopwatch类,它允许用它的.Start()和.Stop()方法轻松计算一段代码。

但是,以正常方式使用Stopwatch类需要我使用Stopwatch对象的实例来装饰每个方法,并调用它的.Start()和.Stop()方法。

我需要在数百种方法上使用秒表功能,并且不希望使用此代码污染每个方法。我也想有能力打开和关闭时间。

有一种简单的方法可以在我自己的代码中实现通用的时序解决方案吗?如果是这样,怎么样?代码分析器可以做到,所以我认为它必须是可能的。

2 个答案:

答案 0 :(得分:8)

只是一个想法。声明一个方法如下

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

并用作

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

答案 1 :(得分:1)

您还可以查看AOP并动态创建Timing方法的包装器(但仅适用于非静态公共方法)。

如果您正在使用IoC,您基本上只需要使用装饰器注册类型,这当然可以自定义并在需要时打开和关闭,甚至是特定方法。

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

编辑:一个例子(来自旧版本的城堡:动态代理)

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