簡體   English   中英

C#秒表錯誤?

[英]C# stopwatch bug?

當我制作一個包含方法的數組時,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

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

這將在Stopwatch之前直接調用method1()method2()

嘗試

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);      
}

我假設您正在嘗試對一組返回int的方法進行基准測試。 你可以做這樣的事情

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);      
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM