StopWatch类计时(误差在2ms以内)
StopWatch可以测量一个间隔的已用时间,或跨多个间隔测量已用总时间。
public static void getTime() { Stopwatch stopWatch = new Stopwatch(); //初始化 TimeSpan ts = stopWatch.Elapsed; //时间间隔 stopWatch.Start(); //开始计时 Thread.Sleep(1000); //需要测时的代码 stopWatch.Stop(); //停止计时,计时器暂停 string elapsedTime1 = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Debug.WriteLine("运行时间:"+ elapsedTime1); stopWatch.Start(); //计时器继续计时,时间累计
Thread.Sleep(1000); //需要测时的代码 string elapsedTime2 = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Debug.WriteLine("运行时间:"+ elapsedTime2); }
输出:
运行时间: 00:00:01.00
运行时间: 00:00:02.00
若想清空计时器则使用
stopWatch.Reset(); //停止计时,计时器重置为0 stopWatch.Restart(); //停止计时,计时器重置为0,并重新开始计时
延时方法:
DelayMs(1000); //延时1000毫秒
DelayMs(); //延时200毫秒
public void DelayMs(int iTime = 200) { bool isOutTime = false; System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Reset(); sw.Start(); //sw.Restart();
long span;
do { span = sw.ElapsedMilliseconds; if (span > iTime && iTime > 0) { isOutTime = true; } Application.DoEvents(); } while (!isOutTime); }
标签:00,sw,ts,计时器,计时,stopWatch From: https://www.cnblogs.com/RoilyaHazal/p/18048317