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 に答える