我在进行一些单元测试时遇到了DateTime.UtcNow的一些意外行为.看起来当你快速连续调用DateTime.Now/UtcNow时,它似乎会给你一个长于预期的时间间隔的相同值,而不是捕获更精确的毫秒增量.
我知道有一个秒表类更适合做精确的时间测量,但我很好奇是否有人可以在DateTime中解释这种行为?是否有针对DateTime.Now记录的官方精度(例如,精确到50毫秒内?)?为什么DateTime.Now会不像大多数CPU时钟那样精确?也许它只是为最低公分母CPU而设计的?
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();
}
Run Code Online (Sandbox Code Playgroud) 在Windows窗体应用程序中,调用的影响Thread.Sleep(1)如下面的代码所示:
public Constructor()
{
Thread thread = new Thread(Task);
thread.IsBackground = true;
thread.Start();
}
private void Task()
{
while (true)
{
// do something
Thread.Sleep(1);
}
}
Run Code Online (Sandbox Code Playgroud)
这个线程会占用所有可用的CPU吗?
我可以使用哪些分析技术来测量此线程的CPU使用率(除了任务管理器)?
有没有办法确定DateTime.Now的两个刻度之间的最小经过时间?我可以用秒表计时,但是有一些方法可以让操作系统在.NET中报告这个吗?
换句话说 - DateTime.Now有多准确?
更新
这很重要,因为我正在编写一个DateTimePrecision类,它存储DateTime.Now,来自StopWatch的滴答,以及秒表每秒钟的常数.在两个DateTimePrecision值之间计算TimeSpan时,如果差异小于DateTime.Now的量程,则使用秒表,否则使用DateTime.Now.
更新
DateTime如果你要比较两次,有几个人已经质疑为什么必须使用它.
原因是它StopWatch会在数小时或数天内缓慢漂移,直到你的时间为秒.
我通过存储两个校正该DateTime和Stopwatch中的结构,并且使用度量来返回一个这是目前或者最精确的,或最准确的.
这样我有:
在我的计时器类中,如果比较两次以计算增量,则切换点由考虑的度量确定System.Runtime.IOThreadTimer.GetSystemTimeResolution().
A和B两次之间的增量绝对误差:
System.Runtime.IOThreadTimer.GetSystemTimeResolution()是几十毫秒.再次,Stopwatch如果你在很多天里测量,依靠它本身将导致几秒钟的增量.
更新
如果您自己实现这一点,请确保您确定也存储Stopwatch.Frequency在结构中.如果您更换硬件或更改操作系统,这可能会改变.如果您持久保存DateTimePrecision实例,则无法知道刻度线的进入速度,您将无法在另一台计算机上读取它们.
这是我到目前为止的测试代码:
using System;
using System.Diagnostics;
using System.IO;
using MyLogType;
using ProtoBuf;
namespace DateTimePrecisionNamespace
{
/// <summary>
/// This class returns a precision time.
/// This class combines the best of both worlds, both precision and accuracy.
/// - It contains a …Run Code Online (Sandbox Code Playgroud)