使用这种模式编写此方法的更好方法是什么?

时间:2014-06-09 02:42:14

标签: c#

我写了很多方法,我想知道它们运行需要多长时间。

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

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

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

4 个答案:

答案 0 :(得分:1)

使用StopWatch类。

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

你可以对代码行做多少......你需要一行来启动计时器,一行停止计时器,一行打印结果。

您可以将方法传递给需要Func<T>的计时器函数,但是您需要一堆重载来处理您的方法可能具有的所有不同签名,并且它将会困扰你的设计。比它值得更麻烦。

答案 1 :(得分:0)

如果您有很多这些方法,并希望能够在登录和注销之前/之后关闭此方法,您可以查看Aspect Oriented Programming

答案 2 :(得分:0)

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

答案 3 :(得分:0)

您可以利用带有句柄对象的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(); }