我有执行不同操作的简短代码,我想测量执行每个操作所需的时间。我在这里阅读了有关秒表类的信息,并且想要优化我的时间测量。
我的函数调用了 5 个其他函数,我想在不声明的情况下测量每个函数:
stopwatch sw1 = new stopwatch();
stopwatch sw2 = new stopwatch();
etc..
我的函数看起来像这样:
public bool func()
{
....
func1()
func2()
....
....
func5()
}
有没有一种方法可以使用一个秒表实例来测量时间?
thanks!!
Use 代表们将方法作为参数传递给函数。
这里我使用了 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++)
{
}
}
}
通过使用它,您可以传递任何您想要的方法。
希望有帮助!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)