您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

用委托或lambda包装秒表计时?

用委托或lambda包装秒表计时?

如何扩展码表类?

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

您可以添加一个重载,该重载忽略“ iterations”参数,并使用一些认值(例如1000)调用此版本。

其他 2022/1/1 18:15:48 有575人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶