9

(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.

Royi Namir
  • 144,742
  • 138
  • 468
  • 792

2 Answers2

5

DateTime has a precision of 100ns. But on typical implementations, DateTime.Now only changes every few milliseconds.

Datetime.Now != Datetime.Now can be true, but it's extremely unlikely to happen. This is a typical race conditions of the kind you often see in multi-threaded code. i.e. you should not rely on DateTime.Now not changing, but rather store a copy in a local variable.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • is it related to computer frequency clock somehow ? – Royi Namir Nov 06 '12 at 11:10
  • It's related to an internal system timer which affects timers, `Thread.Sleep`, `DateTime.Now`, `Environment.TickCount`, thread switching,... – CodesInChaos Nov 06 '12 at 11:12
  • If i remember correctly `DateTime.Now` is relatively expensive since it uses IO. Another reason to store a copy. Edit: Here's the link i'm referring to: http://stackoverflow.com/q/10899709/284240 – Tim Schmelter Nov 06 '12 at 11:17
  • 1
    @TimSchmelter It's expensive because it needs to do time zone conversion. AFAIK the actual time getting part is rather cheap. On my comp `DateTime.UtcNow` costs 9ns, `DateTime.Now` costs 900ns. – CodesInChaos Nov 06 '12 at 11:20
4

DateTime.Now calls internally :

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. 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. But I, personally, never met this kind of condition in my experience.

Community
  • 1
  • 1
Tigran
  • 61,654
  • 8
  • 86
  • 123
  • 1
    well, no :) if someone would ask a question like this, I can give only **guesses**, don't know what the guy in front will figure out about me after this :) – Tigran Nov 06 '12 at 11:35