.NET system.diagnostics 秒表问题
我正在尝试创建一个包含秒表类使用的应用程序。
Stopwatch sw = new Stopwatch();
sw.Start();
while (play)
{
long timer = sw.ElapsedMilliseconds;
Debug.WriteLine(timer);
}
当我测试这个循环并检查经过的时间时,我发现程序缺少一些毫秒。
调试器输出的一些时钟:
31
32
33
34
35
36
37
38
40 <------39 错过
41
42
43
关于如何解决这个问题有什么建议吗?
i am trying to create an application which incorporates the use of the stopwatch class.
Stopwatch sw = new Stopwatch();
sw.Start();
while (play)
{
long timer = sw.ElapsedMilliseconds;
Debug.WriteLine(timer);
}
When i tested this loop and checked the elapsed time, i discovered that the program is missing some milliseconds.
some clockings from the debugger output:
31
32
33
34
35
36
37
38
40 <------39 missed
41
42
43
Any suggestions on how i can solve this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您损失的毫秒数是由于您的程序不是唯一在操作系统上运行的程序这一事实造成的。
因此,有时其他程序会获得它们的时间片,并且会遗漏几毫秒。
你无法“修复”它。
The miliseconds you're losing is due to the fact that your program isn't the only one running on the OS.
So, once in a while other programs get their time slice, and a few mililseconds are left out.
You can't "fix" it.
缺少毫秒?您是否希望看到每毫秒的一个条目?例如每秒 1000 个?如果是这样的话,那将永远不会发生。没有精确到1毫秒的计时API。
事实上,除了任务切换等其他操作系统进程之外,您还在输出毫秒数据的循环中进行分配和流输出,这意味着毫秒精度是不可能的。您需要一台专用的实时机器来完成您正在寻找的输出类型
Missing milliseconds? Are you expecting to see a entry for every single millisecond tick for a second? E.g. 1000 per second? If so then that will never happen. There is no timing API that is accurate to 1 millisecond.
The fact that you're doing an assignment as well as stream output in the loop where you're outputting the millisecond data in addition to other operating system processes such as task switching means that millisecond accuracy is not possible. You would need a dedicated, real-time machine to pull off the kind of output you're looking for
Debug.WriteLine 可能慢于 1 毫秒。它没有针对速度进行优化。
您可以添加一个调用,将消息放入列表中,然后在运行后将列表写入 Debug.WriteLine。
您可以添加一个后台任务,将消息发送到 Debug.WriteLine。
两者都应该防止计时器错过滴答声。
缺少刻度的另一个原因可能是操作系统或另一个程序在两个 Debug.WriteLine 调用之间执行某些工作。它甚至可能是一台运行缓慢的机器。
设置线程优先级或在专用计算机上运行此应用程序应该会有所帮助,但在 Windows 上预计会出现此类计时器问题,因为它从未说过它是实时操作系统。
A Debug.WriteLine can be slower then 1 millisecond. It isn't optimized for speed.
You could add a call placing the message to a list and then write the list to Debug.WriteLine after running.
You could add a background task sending the message to Debug.WriteLine.
Both should prevent the timer from missing ticks.
Another reason for missing ticks might be the OS or another program doing some work between two Debug.WriteLine calls. It might even be a slow machine.
Setting the Thread Priority or running this application on a Dedicated machine should help but these kind of timer issues are expected on Windows since it never said it was a Real Time OS.