C# 秒表显示不正确的时间 [英] C# Stopwatch shows incorrect time

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

问题描述

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

但我的程序产生以下结果

for (int i = 0; i <20; ++i){秒表 sw = Stopwatch.StartNew();日期时间开始 = 日期时间.现在;线程.睡眠(5000);sw.停止();Console.Out.WriteLine("秒表差异:" +sw.ElapsedMilliseconds.ToString());Console.Out.WriteLine("日期时间差异:" +DateTime.Now.Subtract(start).TotalMilliseconds.ToString());}

<小时><前>秒表差异: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.

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆