gpt4 book ai didi

c# - 谜: DateTime precision is rounded when it wants to

转载 作者:太空宇宙 更新时间:2023-11-03 10:47:08 25 4
gpt4 key购买 nike

我一直在使用高精度时间在控制台中记录我的程序事件。但很快我就注意到程序有时会显示四舍五入到毫秒的时间,有时则不会!它完全偶尔发生,它是相同的代码,未重新编译,未在运行之间编辑:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace DateTimePrecisionTest
{
class Program
{
static DateTime ProgramStartTimeGlobal;

static void PrintConsoleLogGlobal()
{
string TimeStampText = ((DateTime.Now - ProgramStartTimeGlobal).TotalMilliseconds / 1000).ToString("0.000000");
Console.WriteLine(String.Format("Global var: [ {0,10} ] ", TimeStampText));
}

static void PrintConsoleLogLocal(DateTime StartTime)
{
string TimeStampText = ((DateTime.Now - StartTime).TotalMilliseconds / 1000).ToString("0.000000");
Console.WriteLine(String.Format("Local var: [ {0,10} ] ", TimeStampText));
}

static void Main(string[] args)
{
ProgramStartTimeGlobal = DateTime.Now;
for (int i = 0; i < 20; i++)
{
PrintConsoleLogGlobal();
PrintConsoleLogLocal(ProgramStartTimeGlobal);
Thread.Sleep(512);
}
Console.ReadLine();
}
}
}

首先我认为这取决于我打印的是全局变量还是局部变量。但似乎并非如此。输出是(值大括号以秒为单位):

enter image description here enter image description here

这种困惑的精度变化发生在其他使用这种日志记录的程序中。例如,这个程序在远程服务器上执行任务(它们之间有不可预测的延迟):

enter image description here enter image description here

为什么??

最佳答案

在内部,DateTime.Now(通过 UtcNow )取决于 Windows API GetSystemTimeAsFileTime .不幸的是,看起来(请参阅该页面底部的社区评论)此时钟的分辨率可能会根据您系统上其他程序的事件而有所不同。

timeBeginPeriod函数记录为:

This function affects a global Windows setting. Windows uses the lowest value (that is, highest resolution) requested by any process.

关于c# - 谜: DateTime precision is rounded when it wants to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22989030/

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