1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Stopwatch的使用 8 { 9 class Program 10 { 11 12 /// <summary> 13 /// 使用Stopwatch比較for循環和foreach循環的效率 14 /// </summary> 15 /// <param name="args"></param> 16 static void Main(string[] args) 17 { 18 19 int[] intArr = new int[1000000]; 20 for (int i = 1; i <= 1000000; i++) 21 { 22 intArr[i - 1] = i; 23 } 24 25 //使用Stopwatch統計程序運行的時間 26 /* 27 Stopwatch提供了幾個方法用以控制Stopwatch對象。 28 * Start方法開始一個計時操作,Stop方法停止計時。 29 * 此時如果第二次使用 Start方法,將繼續計時,最終的計時結果為兩次計時的累加。 30 * 為避免這種情況,在第二次計時前用Reset方法將對象歸零。這三個方法都不需要參數 31 */ 32 System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); 33 sw.Start(); //開始計時 34 35 int sum = 0; 36 37 for (int i = 1; i <= intArr.Length; i++) 38 { 39 sum += i; 40 } 41 Console.WriteLine("sum={0}",sum); 42 43 sw.Stop(); //停止計時 44 long result = sw.ElapsedMilliseconds;//獲得程序運行的時間 45 Console.WriteLine("使用for循環計算從1加到1000000的和所需要的時間是:{0}", result); 46 47 Console.WriteLine("****************************************************************"); 48 sw.Reset(); 49 sw.Start(); 50 51 sum = 0; 52 foreach (var item in intArr) 53 { 54 sum += item; 55 } 56 Console.WriteLine("sum={0}", sum); 57 Console.WriteLine("使用foreach循環計算從1加到1000000的和所需要的時間是:{0}", sw.ElapsedMilliseconds); 58 sw.Stop(); 59 60 Console.ReadKey(); 61 } 62 } 63 }