C#计算一段程序运行时间的三种方法(转)

tech2026-08-11  1

第一种方法利用System.DateTime.Now

public static void SubTest() { DateTime beforeDT = System.DateTime.Now; int[] a = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; //Shuffle(a) is the function you want to test. Shuffle(a); DateTime afterDT = System.DateTime.Now; TimeSpan ts = afterDT.Subtract(beforeDT); Console.WriteLine("DateTime costed for Shuffle function is: {0}ms",ts.TotalMilliseconds); }

第二种用Stopwatch类(System.Diagnostics)

public static void SubTest() { Stopwatch sw = new Stopwatch(); sw.Start(); //Shuffle(a) is the function you want to test. int[] a = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; Shuffle(a); sw.Stop(); TimeSpan ts = sw.Elapsed; Console.WriteLine("DateTime costed for Shuffle function is: {0}ms", ts.TotalMilliseconds); }

 

最新回复(0)