C# 秒表显示不正确的时间

发布于 2024-09-15 12:28:32 字数 791 浏览 3 评论 0原文

我看到其他用户帖子显示秒表测量“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 秒。是线程实际运行的时间吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心碎无痕… 2024-09-22 12:28:32

Stopwatch 类是 不可靠

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

The Stopwatch class is not reliable.

This is unreliable on processors that do not have a constant clock speed (most processors can reduce the clock speed to conserve energy). This is explained in detail here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文