I know that DateTime.UtcNow
does not have a relatively high degree of precision (10-15 ms resolution).
This is a problem for me because in my log files, I want better resolution for the purposes of resolving race conditions.
The question is: how can I get the current date/time with a better precision than what DateTime.UtcNow
offers?
The only solution which I've seen up till now has been this: https://stackoverflow.com/a/15008836/270348. Is that a suitable way to solve the problem?
From MSDN you'll find that DateTime. Now has an approximate resolution of 10 milliseconds on all NT operating systems. The actual precision is hardware dependent.
The datetime precision specifies number of digits after the decimal dot and can be any integer number from 0 to 6. If no precision is specified it is assumed to be 0, for backward compatibility reasons. A datetime precision can be specified wherever a type name is used.
First, lets take a look at precision: The DateTime type is basically just a 64 bit integer that counts “ticks”. One tick is 100 nanoseconds (or 0.0001 milliseconds) long (MSDN). So DateTime 's precision can be up to 0.0001 milliseconds.
If the DateTime object has its Kind property set to Unspecified , its ticks represent the time elapsed time since 12:00:00 midnight, January 1, 0001 in the unknown time zone. In general, the ticks represent the time according to the time zone specified by the Kind property.
You can use Stopwatch
for more precise measurements of time. You can then have each log entry record the time from the start of the first operation. If it's important, you can record the DateTime
of the first operation and therefore calculate the times of the rest, but it sounds like just having the ticks/nanoseconds since the start of the first operation is good enough for your purposes.
If you want to add tracing you could write your own ETW Trace Provider like here. Then you do not need to take care how the timing is fetched. The Windows Kernel will take care that the timing is accurate and the order of the events is correct.
If you do not want to write your own ETW Provider you can use EventSource which is available as Nuget Package which allows you to use it from .NET 4.0 as well. More infos has Vance Morrison on his blog.
When use ETW events then you get a powerful trace analyzer for free with the Windows Performance Toolkit. As added bonus you can do system wide profiling in all processes with minimal impact as well.
This allows you to selectively add call stacks for every event you write which can be invaluable when you want to track down who did call your Dispose method two times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With