C#秒表显示错误的时间

时间:2010-08-20 21:17:43

标签: c# multithreading timer stopwatch

我看过其他用户帖子显示秒表在“Thread.Sleep(5000)”中花费的时间约为5000毫秒。

但我的程序会产生以下结果

for (int i = 0; i < 20; ++i)
{
    Stopwatch sw = Stopwatch.StartNew();
    DateTime start = DateTime.Now;
    Thread.Sleep(5000);
    sw.Stop();
    Console.Out.WriteLine(
        "StopWatch Diff:" + 
        sw.ElapsedMilliseconds.ToString()); 
    Console.Out.WriteLine(
        "DateTime Diff:" + 
        DateTime.Now.Subtract(start).TotalMilliseconds.ToString());
}

StopWatch Diff:1684
DateTime Diff:5262.592
StopWatch Diff:1625
DateTime Diff:4997.12
StopWatch Diff:1604
DateTime Diff:4997.12
StopWatch Diff:1601
DateTime Diff:4997.12
StopWatch Diff:1690
DateTime Diff:4997.12
StopWatch Diff:1603

观察这种行为只是我吗?为什么秒表在实际经过5秒时测量为1.6秒。这是线程实际运行的时间吗?

1 个答案:

答案 0 :(得分:19)

Stopwatch班级为not reliable

  

在没有恒定时钟速度的处理器上这是不可靠的(大多数处理器可以降低时钟速度以节省能量)。这将详细解释here