用这种模式编写这个方法的更好方法

本文关键字:方法 更好 模式 | 更新日期: 2023-09-27 18:07:44

我写了很多方法,我想计算一下它们运行的时间。

     public void myMethod(){
         startTiming();
         doLotsOfStuff();
         stopTiming();
     }

我不仅计时,我还在doLotsOfStuff()方法前后做了一些其他的事情。

我想知道在c#中是否有更好/更聪明的方法来实现这个特定模式所需的更少的行数/编码。

用这种模式编写这个方法的更好方法

使用StopWatch类

var s = new StopWatch();
public void myMethod(){
     s.Start();
     doLotsOfStuff();
     s.Stop();
     Debug.Print(s.Elapsed.ToString());
 }

你对代码行做不了什么…您需要一行来启动计时器,一行来停止计时器,还有一行来打印结果。

你可以将你的方法传递给一个带有Func<T>的计时器函数,但是你需要一堆重载来处理你的方法可能拥有的所有不同的签名,这会混淆你的设计。不值得。

如果你有很多这样的方法,并且希望能够在登录和关闭之前/之后打开它,你可以看看面向方面编程

如果您正在处理许多类似的方法,例如没有参数,那么您可以创建一个基准测试方法,如Robert Harvey详细,但它接受委托。然后你的方法只需要调用委托,而不是直接调用它。作为一种选择,您可以让该方法返回TimeSpan(它是StopWatch内的时间度量),或者返回StopWatch本身。

您可以利用using构造和句柄对象来大致测量通过其代码块所需的时间。

...
using (new TimerHandle(time => /* timing behavior */)) {
    doLotsOfStuff();
}
...
class TimerHandle : IDisposable
{
    private readonly Action<TimeSpan> callback
    private readonly Stopwatch timer;
    public TimerHandle(Action<TimeSpan> callback)
    {
        this.callback = callback;
        this.timer = new Stopwatch();
        this.timer.Start();
    }
    public void Dispose()
    {
        timer.Stop();
        callback(timer.Elapsed);
    }
}

重读你的问题后,我注意到你正在寻找在问题代码之前和之后执行行为。您可能需要考虑包装TimerHandle,以便单个方法或属性可以执行此类行为。

static IDisposable Measure
{
    get
    {
        // before behavior
        return new TimerHandle(time => {
            // timing behavior
            // after behavior
        });
    }
}
using (Measure) { doLotsOfStuff(); }
using (Measure) { andOtherStuff(); }