如何在 C# 中多次使用 StopWatch? [英] How to use StopWatch multiple times in C#?
问题描述
我有执行不同操作的短代码,我想测量执行每个操作所需的时间.我在这里阅读了有关秒表课程的信息,并希望优化我的时间测量.我的函数调用其他 5 个函数,我想在不声明的情况下测量每个函数:
I have short code that performs different operations and I want to measure the time that takes to perform each. I read here about Stopwatch class, and wanted to optimize my time measurements. my functions calls 5 other functions and I want to measure each without declaring :
stopwatch sw1 = new stopwatch();
stopwatch sw2 = new stopwatch();
etc..
我的函数看起来像这样:
my function looks like that:
public bool func()
{
....
func1()
func2()
....
....
func5()
}
有没有办法用一个秒表实例来测量时间?
is there any way to measure the time using one stopwatch instance?
谢谢!!
推荐答案
使用委托将方法作为参数传递给函数.
Use delegates to pass a method as a parameter to a function.
这里我使用了 Action Delegates,因为指定的方法不返回值.
Here I used Action Delegates as the methods specified does not return a value.
如果您的方法具有返回类型或参数,您可以使用函数委托
You can modify it accordingly if your method has a return type or parameter by using a Function delegate
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++)
{
}
}
}
通过使用它,你可以传递任何你想要的方法.
By using this you could pass any method you want.
希望有帮助!
这篇关于如何在 C# 中多次使用 StopWatch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!