如何评测C#中的嵌套循环



我正在尝试评测c#代码中的嵌套foreach循环。如何通过内部(第二(循环测量总时间(每次迭代的总和(

using System;
using System.Diagnostics;
public class Hello 
{
public static void Main() 
{
string[] authors = { "Mike Gold", "Don Box", "Sean", "Harp" };       
Stopwatch stopwatchForDb = new Stopwatch();
stopwatchForDb.Start();                        
foreach (var name in authors)
{          
string[] authorsTwo = { "Tom", "Jerry","Banny"};
stopwatchForDb.Restart();      

//want to print total time taken by this loop in complete program 
foreach (var nameTwo in authorsTwo)
{   
Console.WriteLine(name2);              
}

TimeSpan ts = stopwatchForDb.Elapsed;
Console.WriteLine(ts);
}
Console.WriteLine(name);
}
}

试试这个代码:

string[] authorsTwo = { "Tom", "Jerry", "Banny" };
foreach (var name in authors)
{
stopwatchForDb.Restart();
foreach (var nameTwo in authorsTwo)
{
Console.WriteLine(nameTwo);
Thread.Sleep(1000); //This line is for test output and is not required
}
stopwatchForDb.Stop();
TimeSpan timeTaken = stopwatchForDb.Elapsed;
Console.WriteLine("total time of loop is:{0}", timeTaken.ToString(@"m:ss.fff"));
}

最新更新