C# 测试代码执行时间的两个方法
DateTime startTime = DateTime.Now; Console.WriteLine ("Started: {0}", startTime); // Execute the task to be timed for (int i=1; i < 100000; i++){} DateTime stopTime = DateTime.Now; Console.WriteLine ("Stopped: {0}", stopTime); TimeSpan elapsedTime = stopTime - startTime; Console.WriteLine ("Elapsed: {0}", elapsedTime); Console.WriteLine ("in hours :" + elapsedTime.TotalHours); Console.WriteLine ("in minutes :" + elapsedTime.TotalMinutes); Console.WriteLine ("in seconds :" + elapsedTime.TotalSeconds); Console.WriteLine ("in milliseconds:" + elapsedTime.TotalMilliseconds);
In C# 2.0, 同样的功能可以通过下面的代码实现:
Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 1; i < 1000000; i++) { } // Execute the task to be timed watch.Stop(); Console.WriteLine("Elapsed: {0}",watch.Elapsed); Console.WriteLine("In milliseconds: {0}",watch.ElapsedMilliseconds); Console.WriteLine("In timer ticks: {0}",watch.ElapsedTicks);