C#秒表显示不正确的时间 [英] C# Stopwatch shows incorrect time
本文介绍了C#秒表显示不正确的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到其他用户的帖子这显示出花Thread.sleep代码(5000)是大约5000毫秒秒表测量时间。
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
难道只是我,谁是观察这种行为?为什么秒表过5秒钟实际传递的措施1.6秒。这是该线程实际运行时间?
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?
推荐答案
这是没有一个恒定的时钟速率的处理器不可靠的(大多数处理器可以降低时钟速度以节约能源)。中对此有详细这里解释。
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屋!
查看全文