如何在C#中多次使用StopWatch?

我有简短的代码执行不同的操作,我想测量执行每个操作所需的时间.我在这里读到关于Stopwatch类,并希望优化我的时间测量.
我的函数调用另外5个函数,我想测量每个函数,而不声明:
stopwatch sw1 = new stopwatch();
stopwatch sw2 = new stopwatch();
etc..

我的功能看起来像这样:

public bool func()
{
 ....
 func1()
 func2()
 ....
 ....
 func5()
}

有没有办法使用一个秒表实例测量时间?

谢谢!!

解决方法

使用代理将方法作为参数传递给函数.

这里我使用Action Delegates作为指定的方法不返回值.

如果您的方法通过使用函数委托具有返回类型或参数,则可以相应地进行修改

static void Main(string[] args)
    {
        Console.WriteLine("Method 1 Time Elapsed (ms): {0}",TimeMethod(Method1));
        Console.WriteLine("Method 2 Time Elapsed (ms): {0}",TimeMethod(Method2));
    }

    static long TimeMethod(Action methodToTime)
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        methodToTime();
        stopwatch.Stop();
        return stopwatch.ElapsedMilliseconds;
    }

    static void Method1()
    {
        for (int i = 0; i < 100000; i++)
        {
            for (int j = 0; j < 1000; j++)
            {
            }
        }
    }

    static void Method2()
    {
        for (int i = 0; i < 5000; i++)
        {
        }
    }
}

通过使用它,您可以传递任何您想要的方法.

希望有帮助!

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...