C# 秒表显示不正确的时间
我看到其他用户帖子显示秒表测量“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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Stopwatch 类是 不可靠。
The Stopwatch class is not reliable.