简体   繁体   English

DateTime精度?

[英]DateTime precision?

(ignoring the optimized compiler flag ) (忽略优化的编译器标志)

can it be that this code will enter the block on some systems ? 是不是这个代码会进入某些系统的块?

if (Datetime.Now!=Datetime.Now)
{
 ...
}

I mean , how does it evaluate the values here ? 我的意思是,它如何评估这里的价值观? (is it by order) ? (按顺序)?

Is there any situations where the condition might be true ? 有什么情况可能是真的吗?

again , ignore the optimized flag. 再次, 忽略优化标志。

DateTime has a precision of 100ns. DateTime的精度为100ns。 But on typical implementations, DateTime.Now only changes every few milliseconds. 但在典型的实现中, DateTime.Now仅每隔几毫秒更改一次。

Datetime.Now != Datetime.Now can be true, but it's extremely unlikely to happen. Datetime.Now != Datetime.Now可以是true,但它极不可能发生。 This is a typical race conditions of the kind you often see in multi-threaded code. 这是您经常在多线程代码中看到的那种典型竞争条件。 ie you should not rely on DateTime.Now not changing, but rather store a copy in a local variable. 即你不应该依赖DateTime.Now不改变,而是将副本存储在局部变量中。

DateTime.Now calls internally : DateTime.Now内部调用:

public static DateTime Now
{
    get
    {
        return DateTime.UtcNow.ToLocalTime();
    }
}

which calls internally: 在内部调用:

public static DateTime UtcNow
{
    get
    {
        long systemTimeAsFileTime = DateTime.GetSystemTimeAsFileTime();
        return new DateTime((ulong)(systemTimeAsFileTime + 504911232000000000L | 4611686018427387904L));
    }
}

where GetSystemTimeAsFile is WindowsAPI function that return system clock information. 其中GetSystemTimeAsFile是返回系统时钟信息的WindowsAPI函数。 The accurasy depends on system, so. 准确取决于系统,所以。

If you have a delay, for some reason between different gets ( DateTime.Now ) it may produce different enough result that equality comparer fails. 如果你有一个延迟,由于某种原因在不同的gets( DateTime.Now )之间,它可能产生足够不同的结果,相等比较器失败。 But I, personally, never met this kind of condition in my experience. 但就我个人而言,在我的经历中从未遇到过这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM