C#DateTime.Now精度我在進(jìn)行一些單元測試時遇到了DateTime.UtcNow的一些意外行為??雌饋懋?dāng)你快速連續(xù)調(diào)用DateTime.Now/UtcNow時,它似乎會給你一個長于預(yù)期的時間間隔的相同值,而不是捕獲更精確的毫秒增量。我知道有一個秒表類更適合做精確的時間測量,但我很好奇是否有人可以在DateTime中解釋這種行為?是否有針對DateTime.Now記錄的官方精度(例如,精確到50毫秒內(nèi)?)?為什么DateTime.Now會不像大多數(shù)CPU時鐘那樣精確?也許它只是為最低公分母CPU而設(shè)計的?public static void Main(string[] args){
var stopwatch = new Stopwatch();
stopwatch.Start();
for (int i=0; i<1000; i++)
{
var now = DateTime.Now;
Console.WriteLine(string.Format(
"Ticks: {0}\tMilliseconds: {1}", now.Ticks, now.Millisecond));
}
stopwatch.Stop();
Console.WriteLine("Stopwatch.ElapsedMilliseconds: {0}",
stopwatch.ElapsedMilliseconds);
Console.ReadLine();}
3 回答

ITMISS
TA貢獻(xiàn)1871條經(jīng)驗 獲得超8個贊
DateTime的精度在某種程度上與其運行的系統(tǒng)有關(guān)。精度與上下文切換的速度有關(guān),該速度往往大約為15或16 ms。(在我的系統(tǒng)上,我的測試實際上大約是14毫秒,但我看到一些筆記本電腦的精確度接近35-40毫秒。)
Peter Bromberg寫了一篇關(guān)于 C#中高精度代碼時序的文章,討論了這一點。

瀟湘沐
TA貢獻(xiàn)1816條經(jīng)驗 獲得超6個贊
我想要一個精確的Datetime.Now :),所以我把它煮熟了:
public class PreciseDatetime{ // using DateTime.Now resulted in many many log events with the same timestamp. // use static variables in case there are many instances of this class in use in the same program // (that way they will all be in sync) private static readonly Stopwatch myStopwatch = new Stopwatch(); private static System.DateTime myStopwatchStartTime; static PreciseDatetime() { Reset(); try { // In case the system clock gets updated SystemEvents.TimeChanged += SystemEvents_TimeChanged; } catch (Exception) { } } static void SystemEvents_TimeChanged(object sender, EventArgs e) { Reset(); } // SystemEvents.TimeChanged can be slow to fire (3 secs), so allow forcing of reset static public void Reset() { myStopwatchStartTime = System.DateTime.Now; myStopwatch.Restart(); } public System.DateTime Now { get { return myStopwatchStartTime.Add(myStopwatch.Elapsed); } }}
- 3 回答
- 0 關(guān)注
- 1782 瀏覽
添加回答
舉報
0/150
提交
取消