本文介绍了C# 秒表显示不正确的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到其他用户帖子显示秒表测量在Thread.Sleep(5000)"中花费的时间约为 5000 毫秒.

但我的程序产生以下结果

for (int i = 0; i 

秒表差异:1684日期时间差异:5262.592秒表差异:1625日期时间差异:4997.12秒表差异:1604日期时间差异:4997.12秒表差异:1601日期时间差异:4997.12秒表差异:1690日期时间差异:4997.12秒表差异:1603

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

解决方案

秒表不可靠.

这在没有恒定时钟速度的处理器上是不可靠的(大多数处理器可以降低时钟速度以节省能源).此处对此进行了详细说明.

I have seen other user posts which show Stopwatch measuring time spent in "Thread.Sleep(5000)" to be around 5000ms.

But my program produces the following results

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

Is it just me who is observing this behaviour? Why stopwatch measures 1.6 seconds when 5 seconds have actually passed. It is the time that the thread is actually running?

解决方案

The Stopwatch class is not reliable.

这篇关于C# 秒表显示不正确的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-11 23:26