abdolahS
abdolahS

Reputation: 683

speed of calling System.DateTime.Now

when I run the following code it shows the elapsed time equal to zero but when I comment the first line it shows elapsed time equal to 20ms! why?

does calling System.DateTime.Now loads something in runtime and this cause the difference?

string time1 = System.DateTime.Now.ToString();
var sw = System.Diagnostics.Stopwatch.StartNew();
string time = System.DateTime.Now.ToString();
string te = sw.ElapsedMilliseconds.ToString(); ;
Console.WriteLine(te);
sw.Stop();

Upvotes: 2

Views: 1078

Answers (2)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262919

After disassembling mscorlib and analysing the results, that twenty millisecond delay may very well be caused by DateTime.Now.

At least in version 4.0 of the .NET Framework, that property calls the internal TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc() method. That method, in turn, invokes TimeZoneInfo.s_cachedData.GetOneYearLocalFromUtc(), which may exhibit a performance penalty on the first call (when that data is not cached yet).

Depending on the result of that call, TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc() can also invoke TimeZoneInfo.GetIsDaylightSavingsFromUtc(), which is non-trivial and involves date arithmetic.

Upvotes: 1

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

First and foremost, never profile in Debug. Further, even in Release, never profile with the debugger attached. Your results are skewed and hold no real value.

This code, in Release takes 0 milliseconds. I executed it and verified that output. Below is the output:

0
Press any key to continue . . .

Upvotes: 3

Related Questions