gpt4 book ai didi

c# - 为什么 DateTime.Now 和 StopWatch 会漂移?

转载 作者:太空狗 更新时间:2023-10-29 18:31:40 28 4
gpt4 key购买 nike

我用 C# 制作了一个小型测试应用程序,它设置了 DateTime.Now 并启动了一个 StopWatch。每十秒我打印一次 _stopwatch.Elapsed.TotalMilliseconds(DateTime.Now - _startTime).TotalMilliseconds

虽然我不认为两者完全相同,但令我惊讶的是它们每 20 秒线性偏离大约 1 毫秒。我假设 DateTime.Now 调用系统时钟,而 StopWatch 进行某种累积?

示例输出:

StopWatch : 0,2  DateTime : 1,0 Diff : 0,81
StopWatch : 10000,5 DateTime : 10002,6 Diff : 2,04
(...)
StopWatch : 2231807,5 DateTime : 2231947,7 Diff : 140,13
StopWatch : 2241809,5 DateTime : 2241950,2 Diff : 140,70

完整来源:https://gist.github.com/knatten/86529563122a342de6bb

输出:https://gist.github.com/knatten/84f9be9019ee63119ee2

最佳答案

答案相对简单。

  • 秒表使用性能计数器对处理器滴答进行计数,这是一种因处理器而异的机制。
  • DateTime 查询系统时钟 - 系统时钟由 Windows 使用主板上的(可能是 quartz )晶体时钟的输出定期更新。

所有时钟都会漂移,这两种不同的计时机制将以不同的速率漂移。

在引擎盖下,秒表 uses this API

The Stopwatch class assists the manipulation of timing-related performance counters within managed code. Specifically, the Frequency field and GetTimestamp method can be used in place of the unmanaged Win32 APIs QueryPerformanceFrequency and QueryPerformanceCounter.

日期时间 uses this API

关于c# - 为什么 DateTime.Now 和 StopWatch 会漂移?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23390573/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com