结束语秒表计时与委托或lambda?秒表、结束语、lambda

2023-09-02 01:28:38 作者:皇冠夫妇

我在写code这个样子,做一个小的快速和肮脏的时机:

I'm writing code like this, doing a little quick and dirty timing:

var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
    b = DoStuff(s);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);

当然,有一种方法来调用时机code该位为花式schmancy .NET 3.0的lambda,而不是(上帝保佑)剪切和粘贴了几次,并更换 DoStuff(S) DoSomethingElse(S)

Surely there's a way to call this bit of timing code as a fancy-schmancy .NET 3.0 lambda rather than (God forbid) cutting and pasting it a few times and replacing the DoStuff(s) with DoSomethingElse(s)?

我知道这是可以做到为代理,但我想了解一下拉姆达的方式。

I know it can be done as a Delegate but I'm wondering about the lambda way.

推荐答案

如何延长秒表类?

public static class StopwatchExtensions
{
    public static long Time(this Stopwatch sw, Action action, int iterations)
    {
        sw.Reset();
        sw.Start(); 
        for (int i = 0; i < iterations; i++)
        {
            action();
        }
        sw.Stop();

        return sw.ElapsedMilliseconds;
    }
}

然后调用它是这样的:

Then call it like this:

var s = new Stopwatch();
Console.WriteLine(s.Time(() => DoStuff(), 1000));

您可以添加另一个重载它省略了重复的参数,并调用该版本的一些默认值(如1000)。

You could add another overload which omits the "iterations" parameter and calls this version with some default value (like 1000).