如何在C#中多次使用StopWatch?
发布时间:2020-12-15 06:32:04 所属栏目:百科 来源:网络整理
导读:我有简短的代码执行不同的操作,我想测量执行每个操作所需的时间.我在这里读到关于Stopwatch类,并希望优化我的时间测量. 我的函数调用另外5个函数,我想测量每个函数,而不声明: stopwatch sw1 = new stopwatch();stopwatch sw2 = new stopwatch();etc.. 我的
我有简短的代码执行不同的操作,我想测量执行每个操作所需的时间.我在这里读到关于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++) { } } } 通过使用它,您可以传递任何您想要的方法. 希望有帮助! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |