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

use*_*966 10 c# optimization time

我有短代码执行不同的操作,我想测量执行每个操作所需的时间.我在这里读到关于秒表课程,并希望优化我的时间测量.我的函数调用了其他5个函数,我想在不声明的情况下测量每个函数:

stopwatch sw1 = new stopwatch();
stopwatch sw2 = new stopwatch();
etc..
Run Code Online (Sandbox Code Playgroud)

我的功能看起来像这样:

public bool func()
{
 ....
 func1()
 func2()
 ....
 ....
 func5()
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢!!

小智 19

使用委托将方法作为参数传递给函数.

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

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

    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++)
        {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

希望有所帮助!


小智 7

What you need is the Restart function of the Stopwatch class, something like this:

public bool func()
{
    var stopwatch = Stopwatch.StartNew();

    func1();

    Debug.WriteLine(stopwatch.ElapsedMilliseconds);

    stopwatch.Restart();

    func5();

    Debug.WriteLine(stopwatch.ElapsedMilliseconds);
}
Run Code Online (Sandbox Code Playgroud)


oak*_*kio 5

是的,试试这个:

    void func1()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        func1();
        sw.Stop();
        Console.Write(sw.Elapsed);

        sw.Restart();
        func2();
        sw.Stop();
        Console.Write(sw.Elapsed);
    }
Run Code Online (Sandbox Code Playgroud)

  • 使用"重新启动"停止当前间隔测量并开始新的间隔测量(MSDN).重启将清除已用时间. (3认同)