原文:https://blog.csdn.net/zp19860529/article/details/87862922
public void test2() { //原文:https://blog.csdn.net/zp19860529/article/details/87862922 Stopwatch stopwatch = new Stopwatch(); //第一次计时 stopwatch.Start(); //启动Stopwatch Console.WriteLine("Stopwatch is running:{0}", stopwatch.IsRunning);//获取当前Stopwatch的状态 System.Threading.Thread.Sleep(2000);//耗时操作 stopwatch.Stop(); //停止Stopwatch Console.WriteLine("Using Elapsed output runTime:{0}", stopwatch.Elapsed.ToString());//这里使用时间差来输出,如:时:分:秒 Console.WriteLine("Using ElapsedMilliseconds output runTime:{0}", stopwatch.ElapsedMilliseconds);//这里面使用毫秒来输出 Console.WriteLine("==================================================="); //第二次计时 stopwatch.Start(); System.Threading.Thread.Sleep(1000);//耗时操作 stopwatch.Stop(); Console.WriteLine("The second RunTime:{0}", stopwatch.ElapsedMilliseconds);//这里面使用毫秒来输出 Console.WriteLine("==================================================="); //第三次计时(这里使用了Restart) stopwatch.Restart();//这里使用Restart来启动计时(会把前面的时间清空) System.Threading.Thread.Sleep(1000);//耗时操作 stopwatch.Stop(); Console.WriteLine("After Restart, so runTime:{0}", stopwatch.ElapsedMilliseconds);//这里面使用毫秒来输出 Console.ReadKey(); //等待输入 }
运行结果预览: