微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在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++)
        {
        }
    }
}

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

希望有帮助!

原文地址:https://www.jb51.cc/csharp/95363.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐