用委托或 lambda 包装秒表计时? [英] Wrapping StopWatch timing with a delegate or lambda?

查看:24
本文介绍了用委托或 lambda 包装秒表计时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写这样的代码,时间有点快和脏:

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

当然有一种方法可以将这段时间代码称为花哨的 .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)?

我知道它可以作为 Delegate 完成,但我想知道 lambda 的方式.

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

推荐答案

如何扩展 Stopwatch 类?

How about extending the Stopwatch class?

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;
    }
}

然后这样称呼它:

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).

这篇关于用委托或 lambda 包装秒表计时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆