c#实现统计代码执行时间
2018-07-20 来源:open-open
方法一: //实例化一个计时器 Stopwatch watch = new Stopwatch(); //开始计时 watch.Start(); //此处为要计算的运行代码 for (int i = 1; i < 1000000; i++) { } // Execute the task to be timed //结束计时 watch.Stop(); //获取当前实例测量得出的总运行时间(以毫秒为单位) string time = watch.ElapsedMilliseconds.ToString(); //说明:Stopwatch提供了几个方法用以控制Stopwatch对象。Start方法开始一个计时操作,Stop方法停止计时。为避免这种情况,在第二次计时前用Reset方法将对象归零 Console.WriteLine("Elapsed: {0}",watch.Elapsed); Console.WriteLine("In milliseconds: {0}",watch.ElapsedMilliseconds); Console.WriteLine("In timer ticks: {0}",watch.ElapsedTicks); 方法二: 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);
标签: 代码
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐