I'm making a program in which I need to get the time in milliseconds. By time, I mean a number that is never equal to itself, and is always 1000 numbers bigger than it was a second ago. I've tried converting DateTime.Now
to a TimeSpan
and getting the TotalMilliseconds
from that... but I've heard it isn't perfectly accurate.
Is there an easier way to do this?
You can try the
QueryPerformanceCounter
native method. See http://www.pinvoke.net/default.aspx/kernel32/QueryPerformanceCounter.html for more information. This is what theStopwatch
class uses.See How to get timestamp of tick precision in .NET / C#? for more information.
Stopwatch.GetTimestamp()
gives access to this method:Use the
Stopwatch
class.There is some good info on implementing it here:
Performance Tests: Precise Run Time Measurements with System.Diagnostics.Stopwatch
Use
System.DateTime.Now.ToUniversalTime()
. That puts your reading in a known reference-based millisecond format that totally eliminates day change, etc.I use the following class. I found it on the Internet once, postulated to be the best NOW().
Source unknown.
The
DateTime.Ticks
property gets the number of ticks that represent the date and time.10,000 Ticks is a millisecond (10,000,000 ticks per second).
This is actually how the various Unix conversion methods are implemented in the
DateTimeOffset
class (.NET Framework 4.6+, .NET Standard 1.3+):