A colleague and I are going back and forth on this issue and I\'m hoping to get some outside opinions as to whether or not my proposed solution is a good idea.
First
Could you just use DateTime.UtcNow, and only convert to local time when the data is presented? You've already determined that DateTime.UtcNow is much faster and it will remove any ambiguity around DST.
To answer in reverse order:
2) I cannot think of a faster way.
1) It would be worth checking if there are any framework improvements in the pipeline like they have just announced for System.IO
It's hard to be sure about safety but it's something that is crying out for a lot of unit tests. Daylight savings comes to mind. The System one is obviously very battle hardened while yours is not.
One difference between the result of
DateTime.Now
and
DateTime.UtcNow + LocalUtcOffset
is the value of the Kind property - Local vs Utc respectively. If the resultant DateTime is being passed to a third party library consider returning
DateTime.SpecifyKind(DateTime.UtcNow + LocalUtcOffset, DateTimeKind.Local)
I like your solution.
I made some tests to see how much faster it is compared to regular DateTime.Now
DateTime.UtcNow
is 117 times faster than DateTime.Now
using DateTime.UtcNow
is good enough if we are only interested in the duration and not the time itself. If all we need is to calculate the duration of a specific code section ( doing duration= End_time - Start_time
) then the time zone is not important and DateTime.UtcNow
is sufficient.
But if we need the time itself then we need to do
DateTime.UtcNow + LocalUtcOffset
Just adding the time span slows down a little bit
and now according to my tests we are just 49 times faster than the regular DateTime.Now
If we put this calculation in a separate function/class as suggested then calling the method slows us down even more and we are only 34 times faster.
But even 34 times faster is a lot !!!
In short,
Using DateTime.UtcNow
is much faster than DateTime.Now
The only way I found to improve the suggested class is to use
inline code: DateTime.UtcNow + LocalUtcOffset
instead of calling the class method
BTW trying to force the compiler to compile as inline by using [MethodImpl(MethodImplOptions.AggressiveInlining)]
didnt seem to speed things up.