C# StopWatch的使用(计时,时间间隔)-简记

  Stopwatch 可以测量一个时间间隔的运行时间,也可以测量多个时间间隔的总运行时间。一般用来测量代码执行所用的时间或者计算性能数据,在优化代码性能上可以使用Stopwatch来测量时间。

       引用的空间名:使用的时候需要引用 System.Diagnostics 命名空间。

       先调用 Start 方法,然后调用 Stop 方法,最后使用 Elapsed 属性或者使用 ElapsedMilliseconds 属性得到运行时间(这两个属性的区别是前者得到的是TimeSpan实例,后者得到的是毫秒)。使用 IsRunning 可以确定 Stopwatch 的当前状态是正在运行还是已经停止。每次调用 Start 时开始累计运行时间计数;每次调用 Stop 时结束当前时间间隔测量,并冻结累计运行时间值。 使用 Reset 方法可以清除现有 Stopwatch 实例中的累计运行时间。

示例代码

    

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();  //等待输入

其它相关计时器扩展参考 :https://blog.csdn.net/fuyifang/article/details/45059053

猜你喜欢

转载自blog.csdn.net/zp19860529/article/details/87862922