0

当我创建一个包含方法的数组时,stopwatch.elapsedMilliseconds 总是返回 0。

例子:

int[] methods = {method1(), method2()};

Stopwatch sw = new Stopwatch();

sw.Start();
int val = methods[1];
sw.Stop();

Console.WriteLine("It took {0} ms", sw.ElapsedMilliseconds);
// Output: "It took 0 ms"

当我直接调用该方法时,秒表可以正常工作:

Stopwatch sw = new Stopwatch();

sw.Start();
method1();
sw.Stop();

Console.WriteLine("It took {0} ms", sw.ElapsedMilliseconds);
// Output: "It took x ms"

我究竟做错了什么?

编辑:实际主要代码:

 static void Main(string[] args)
        {
            Stopwatch t = new Stopwatch();
            Func<int>[] problems = new Func<int>[] { problem5, problem6 };


            for (int i = 0; i < problems.Length; i++)
            {
                t.Restart();
                Console.WriteLine("Solution to {0} is: {1}", problems[i].Method.Name , problems[i]());
                t.Stop();
                Console.WriteLine("It took {0} ms ", t.ElapsedMilliseconds);


            }

            Console.ReadKey();


        }

输出: http://puu.sh/3Znwd.png

4

2 回答 2

6
int[] methods = new[] { method1(), method2() };

这个直接打电话method1()method2()Stopwatch

尝试

Func<int>[] methods = new Func<int>[] { method1, method2 };

t.start();
methods[1]();

例子

Func<int>[] methods = new Func<int>[] { method1, method2 };

Stopwatch sw = new Stopwatch();

for(int i = 0; i < methods.Length; i++)
{
    sw.Restart(); // or sw.Reset(); sw.Start();
    methods[i]();
    sw.Stop();

    Console.WriteLine("{0} took {1} ms", allMethods[i].Method.Name, sw.ElapsedMilliseconds);      
}
于 2013-08-11T15:41:33.810 回答
4

我假设您正在尝试对一组返回整数的方法进行基准测试。你可以做这样的事情

Func<int>[] allMethods = new Func<int>[] { method1, method2 };

Stopwatch sw = new Stopwatch();
for(int i =0; i < allMethods.Length; i++)
{
    sw.Restart(); 
    allMethods[i]();
    sw.Stop();

    Console.WriteLine("{0} took {1} ms", allMethods[i].Method.Name, sw.ElapsedMilliseconds);      
}
于 2013-08-11T15:49:47.263 回答