Stopwatch sw = new Stopwatch();
for (int i = 0; i < lines.Length; i++)
{
sw.Start();
fn(); //call function
sw.Stop();
}
Console.WriteLine(sw.ElapsedMilliseconds);
long total =0;
for (int i = 0; i < lines.Length; i++)
{
Stopwatch sw = Stopwatch.StartNew();
fn(); //call function
sw.Stop();
total += sw.ElapsedMilliseconds;
}
Console.WriteLine(total);
輸出是不一樣的,你有沒有任何解釋?秒錶怪異的行爲
對於任何合理長度的fn()(一個值得分析),與循環相關的開銷將可以忽略不計,並且在任何情況下都小於與開始和停止相關的開銷。首先,Start和Stop都有方法調用開銷(假設沒有內聯),而簡單的for循環只是一個增量和比較分支。 – 2010-11-03 16:05:57