两个时间差的高精度检查
1 static void Main(string[] args) 2 { 3 Console.WriteLine("开始时间:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff")); 4 Stopwatch w = new Stopwatch(); 5 w.Start(); 6 Spin(w, 500); 7 Console.ReadKey(); 8 } 9 static void Spin(Stopwatch w, int duration) 10 { 11 var current = w.ElapsedMilliseconds; 12 while ((w.ElapsedMilliseconds - current) < duration) 13 { 14 Thread.SpinWait(1); 15 System.Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff")); 16 } 17 Console.WriteLine("最终时间:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff")); 18 }
运行结果如下
开始时间:
结束时间:
刚刚好相差500毫秒