Up until now I used DateTime.Now for getting timestamps, but I noticed that if you print DateTime.Now in a loop you will see that it increments in descrete jumps of approx. 15 ms. But for certain scenarios in my application I need to get the most accurate timestamp possible, preferably with tick (=100 ns) precision. Any ideas?
Update:
Apparently, StopWatch / QueryPerformanceCounter is the way to go, but it can only be used to measure time, so I was thinking about calling DateTime.Now when the application starts up and then just have StopWatch run and then just add the elapsed time from StopWatch to the initial value returned from DateTime.Now. At least that should give me accurate relative timestamps, right? What do you think about that (hack)?
NOTE:
StopWatch.ElapsedTicks is different from StopWatch.Elapsed.Ticks! I used the former assuming 1 tick = 100 ns, but in this case 1 tick = 1 / StopWatch.Frequency. So to get ticks equivalent to DateTime use StopWatch.Elapsed.Ticks. I just learned this the hard way.
NOTE 2:
Using the StopWatch approach, I noticed it gets out of sync with the real time. After about 10 hours, it was ahead by 5 seconds. So I guess one would have to resync it every X or so where X could be 1 hour, 30 min, 15 min, etc. I am not sure what the optimal timespan for resyncing would be since every resync will change the offset which can be up to 20 ms.
The value of the system clock that DateTime.Now reads is only updated every 15 ms or so (or 10 ms on some systems), which is why the times are quantized around those intervals. There is an additional quantization effect that results from the fact that your code is running in a multithreaded OS, and thus there are stretches where your application is not "alive" and is thus not measuring the real current time.
Since you're looking for an ultra-accurate time stamp value (as opposed to just timing an arbitrary duration), the Stopwatch class by itself will not do what you need. I think you would have to do this yourself with a sort of DateTime/Stopwatch hybrid. When your application starts, you would store the current DateTime.UtcNow value (i.e. the crude-resolution time when your application starts) and then also start a Stopwatch object, like this:
DateTime _starttime = DateTime.UtcNow;
Stopwatch _stopwatch = Stopwatch.StartNew();
Then, whenever you need a high-resolution DateTime value, you would get it like this:
DateTime highresDT = _starttime.AddTicks(_stopwatch.Elapsed.Ticks);
You also may want to periodically reset _starttime and _stopwatch, to keep the resulting time from getting too far out of sync with the system time (although I'm not sure this would actually happen, and it would take a long time to happen anyway).
Update: since it appears that Stopwatch does get out of sync with the system time (by as much as half a second per hour), I think it makes sense to reset the hybrid DateTime class based on the amount of time that passes between calls to check the time:
public class HiResDateTime
{
private static DateTime _startTime;
private static Stopwatch _stopWatch = null;
private static TimeSpan _maxIdle =
TimeSpan.FromSeconds(10);
public static DateTime UtcNow
{
get
{
if ((_stopWatch == null) ||
(_startTime.Add(_maxIdle) < DateTime.UtcNow))
{
Reset();
}
return _startTime.AddTicks(_stopWatch.Elapsed.Ticks);
}
}
private static void Reset()
{
_startTime = DateTime.UtcNow;
_stopWatch = Stopwatch.StartNew();
}
}
If you reset the hybrid timer at some regular interval (say every hour or something), you run the risk of setting the time back before the last read time, kind of like a miniature Daylight Savings Time problem.
To get a high-resolution tick-count, please, use the static Stopwatch.GetTimestamp()-method:
long tickCount = System.Diagnostics.Stopwatch.GetTimestamp();
DateTime highResDateTime = new DateTime(tickCount);
just take a look at the .NET Source Code:
public static long GetTimestamp() {
if(IsHighResolution) {
long timestamp = 0;
SafeNativeMethods.QueryPerformanceCounter(out timestamp);
return timestamp;
}
else {
return DateTime.UtcNow.Ticks;
}
}
Source Code here: http://referencesource.microsoft.com/#System/services/monitoring/system/diagnosticts/Stopwatch.cs,69c6c3137e12dab4
[The accepted answer does not appear to be thread safe, and by its own admission can go backwards in time causing duplicate timestamps, hence this alternative answer]
If what you really care about (per your comment) is in fact, a unique timestamp that is allocated in strict ascending order and which corresponds as closely as possible to the system time, you could try this alternative approach:
public class HiResDateTime
{
private static long lastTimeStamp = DateTime.UtcNow.Ticks;
public static long UtcNowTicks
{
get
{
long orig, newval;
do
{
orig = lastTimeStamp;
long now = DateTime.UtcNow.Ticks;
newval = Math.Max(now, orig + 1);
} while (Interlocked.CompareExchange
(ref lastTimeStamp, newval, orig) != orig);
return newval;
}
}
}
These suggestions all look too hard! If you're on Windows 8 or Server 2012 or higher, use GetSystemTimePreciseAsFileTime as follows:
[DllImport("Kernel32.dll", CallingConvention = CallingConvention.Winapi)]
static extern void GetSystemTimePreciseAsFileTime(out long filetime);
public DateTimeOffset GetNow()
{
long fileTime;
GetSystemTimePreciseAsFileTime(out fileTime);
return DateTimeOffset.FromFileTime(fileTime);
}
This has much, much better accuracy than DateTime.Now without any effort.
See MSDN for more info: http://msdn.microsoft.com/en-us/library/windows/desktop/hh706895(v=vs.85).aspx
It does return the most accurate date and time known to the operating system.
The operating system also provides higher resolution timing through QueryPerformanceCounter and QueryPerformanceFrequency (.NET Stopwatch class). These let you time an interval but do not give you date and time of day. You might argue that these would be able to give you a very accurate time and day, but I am not sure how badly they skew over a long interval.
1). If you need high resolution absolute accuracy: you can't use DateTime.Now
when it is based on a clock with a 15 ms interval (unless it
is possible "slide" the phase).
Instead, an external source of better resolution absolute
accuracy time (e.g. ntp), t1 below, could be combined with the high
resolution timer (StopWatch / QueryPerformanceCounter).
2). If you just need high resolution:
Sample DateTime.Now (t1) once together with a value from the
high resolution timer (StopWatch / QueryPerformanceCounter)
(tt0).
If the current value of the high resolution timer is tt then the
current time, t, is:
t = t1 + (tt - tt0)
3). An alternative could be to disentangle absolute time and
order of the financial events: one value for absolute time
(15 ms resolution, possibly off by several minutes) and one
value for the order (for example, incrementing a value by one each
time and store that). The start value for the order can be
based on some system global value or be derived from the
absolute time when the application starts.
This solution would be more robust as it is not dependent on
the underlying hardware implementation of the clocks/timers
(that may vary betweens systems).
This is too much work for something so simple. Just insert a DateTime in your database with the trade. Then to obtain trade order use your identity column which should be an incrementing value.
If you are inserting into multiple databases and trying to reconcile after the fact then you will be mis-calculating trade order due to any slight variance in your database times (even ns increments as you said)
To solve the multiple database issue you could expose a single service that each trade hits to get an order. The service could return a DateTime.UtcNow.Ticks and an incrementing trade number.
Even using one of the solutions above anyone conducting trades from a location on the network with more latency could possibly place trades first (real world), but they get entered in the wrong order due to latency. Because of this the trade must be considered placed at the database, not at users' consoles.
The 15 ms (actually it can be 15-25 ms) accuracy is based on the Windows 55 Hz/65 Hz timer resolution. This is also the basic TimeSlice period. Affected are Windows.Forms.Timer, Threading.Thread.Sleep, Threading.Timer, etc.
To get accurate intervals you should use the Stopwatch class. It will use high-resolution if available. Try the following statements to find out:
Console.WriteLine("H = {0}", System.Diagnostics.Stopwatch.IsHighResolution);
Console.WriteLine("F = {0}", System.Diagnostics.Stopwatch.Frequency);
Console.WriteLine("R = {0}", 1.0 /System.Diagnostics.Stopwatch.Frequency);
I get R=6E-08 sec, or 60 ns. It should suffice for your purpose.
I'd add the following regarding MusiGenesis Answer for the re-sync timing.
Meaning: What time should I use to re-sync ( the _maxIdle in MusiGenesis answer's)
You know that with this solution you are not perfectly accurate, thats why you re-sync.
But also what you implicitly want is the same thing as Ian Mercer solution's:
a unique timestamp that is allocated in strict ascending order
Therefore the amount of time between two re-sync ( _maxIdle Lets call it SyncTime) should be function of 4 things:
the DateTime.UtcNow resolution
the ratio of accuracy you want
the precision level you want
An estimation of the out-of-sync ratio of your machine
Obviously the first constraint on this variable would be :
out-of-sync ratio <= accuracy ratio
For example : I dont want my accuracy to be worst than 0.5s/hrs or 1ms/day etc... (in bad English: I dont want to be more wrong than 0.5s/hrs=12s/day).
So you cannot achieve a better accuracy than what the Stopwatch offer you on your PC. It depends on your out-of-sync ratio, which might not be constant.
Another constraint is the minimum time between two resync:
Synctime >= DateTime.UtcNow resolution
Here accuracy and precision are linked because if you using a high precision (for example to store in a DB) but a lower accuracy, You might break Ian Mercer statement that is the strict ascending order.
Note: It seems DateTime.UtcNow may have a bigger default Res than 15ms (1ms on my machine) Follow the link:
High accuracy DateTime.UtcNow
Let's take an example:
Imagine the out-of-sync ratio commented above.
After about 10 hours, it was ahead by 5 seconds.
Say I want a microsec precision. My timer res is 1ms (see above Note)
So point by point:
the DateTime.UtcNow resolution : 1ms
accuracy ratio >= out-of-sync ratio,
lets take the most accurate possible so : accuracy ratio = out-of-sync ratio
the precision level you want : 1 microsec
An estimation of the out-of-sync ratio of your machine : 0.5s/hour (this is also my accuracy)
If you reset every 10s, imagine your at 9.999s, 1ms before reset.
Here you make a call during this interval. The time your function will plot is ahead by : 0.5/3600*9.999s eq 1.39ms.
You would display a time of 10.000390sec. After UtcNow tick, if you make a call within the 390micro sec, your will have a number inferior to the previous one. Its worse if this out-of-sync ratio is random depending on CPU Load or other things.
Now let's say I put SyncTime at its minimum value > I resync every 1ms
Doing the same thinking would put me Ahead of time by 0.139 microsec < inferior to the precision I want. Therefore if I call the function at 9.999 ms, so 1microsec before reset I will plot 9.999. And just after I will plot 10.000. I will have a good order.
So here the other constraint is : accuracy-ratio x SyncTime < precision level , lets say to be sure because number can be rounded up that accuracy-ratio x SyncTime < precision level/2 is good.
The issue is resolved.
So a Quick recap would be :
Retrieve your timer resolution.
Compute an estimate of the out-of-sync ratio.
accuracy ratio >= out-of-sync ratio estimate , Best accuracy = out-of-sync ratio
Choose your Precision Level considering the following:
timer-resolution <= SyncTime <= PrecisionLevel/(2*accuracy-ratio)
The best Precision you can achieve is timer-resolution*2*out-of-sync ratio
For the above ratio (0.5/hr) the correct SyncTime would be 3.6ms, so rounded down to 3ms.
With the above ratio and the timer resolution of 1ms. If you want a one-tick Precision level (0.1microsec), you need an out-of-sync ratio of no more than : 180ms/hour.
In its last answer to its own answer MusiGenesis state:
#Hermann: I've been running a similar test for the last two hours (without the reset correction), and the Stopwatch-based timer is only running about 400 ms ahead after 2 hours, so the skew itself appears to be variable (but still pretty severe). I'm pretty surprised that the skew is this bad; I guess this is why Stopwatch is in System.Diagnostics. – MusiGenesis
So the Stopwatch accuracy is close to 200ms/hour, almost our 180ms/hour. Is there any link to why our number and this number are so close ? Dont know. But this accuracy is enough for us to achieve Tick-Precision
The Best PrecisionLevel: For the example above it is 0.27 microsec.
However what happen if I call it multiple times between 9.999ms and the re-sync.
2 calls to the function could end-up with the same TimeStamp being returned the time would be 9.999 for both (as I dont see more precision). To circumvent this, you cannot touch the precision level because it is Linked to SyncTime by the above relation. So you should implement Ian Mercer solution's for those case.
Please don't hesitate to comment my answer.
If need the timestamp to perform benchmarks use StopWatch which has much better precision than DateTime.Now.
I think this is the best way to solve this issue:
long timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
Related
What should be the best way to calculate the time diff which is accurate upto the level of Microseconds. currently I am doing as follows:
((TimeSpan)(DateTime.Now - _perfClock)).TotalMilliseconds
Note: perfClock is DateTime (set prior to task)
Which is suppose to give accuracy upto Milliseconds, but in my case it is showing values ends with "000". like 8000,9000 etc...
This is forcing me to think that is just converting seconds to Milliseconds somewhere, instead of calculating diff in Milliseconds. (Possibly I am wrong somewhere in code above).
But what should be the recommended mechanism for accurate Time Diff calculation?
-Sumeet
The issue is not with TimeSpan, that is accurate down to ticks, which is 100 nanoseconds.
The issue is you are using DateTime.Now for your timer.
DateTime.Now is accurate to about 16ms i believe. as mentioned by V4Vendetta, you want to use Stopwatch if you need "high resolution" results. Stopwatch can provide you with ticks (long) or TimeSpan. use Timespan for easy manipulation (in your case, add/subtract).
Note also that Stopwatch provides a .IsHighResolution property, to see if you have a better accuracy than Datetime.Now (it's always true on PC iirc)
I don't know the context in which you are measuring time but it would be good to start of with Stopwatch and check your results.
Also worth a read Precise Measurement
Have you tried:
TimeSpan diff = DateTime.Now.Subtract(_perfClock);
I am trying to calculate a video framerate in a program. To do this I take
DateTime.Now
at the beginning of a stream, and then again after every frame whilst also incrementing a framecounter.
Then I calculate the FPS like so:
int fps = (int)(frames / (TimeSpan.FromTicks(CurrentTime.Ticks).Seconds - TimeSpan.FromTicks(StartTime.Ticks).Seconds));
The problem is that I occassionally get a negative number out, meaning the start time must be later than the current time. How can this be the case? Does anyone know anough about these functions to explain?
Seconds gives you the seconds part of the TimeSpan, not the total duration of the TimeSpan converted in seconds. This means that Seconds will never be greater than 60.
Use TotalSeconds instead
You should consider using StopWatch for such needs, It has much better precision
The datetime functions are probably not precise enough for your needs, you may want to look into performance counters instead. I think the StopWatch class is what your looking for. System.Diagnostics.StopWatch. that is using the QueryPerformanceFrequency and QueryPerformanceCounter functions for the timing.
We are currently rewritting the core of our services, basically we have scheduled tasks that can run on intervals, dates, specific times etc etc etc.
Currently we're wondering if daylightsaving might cause trouble for us, basically we calculate the next possible runtime, based on what days the task should execute and between what times, and what interval. We do this by taking the current time, and adding days/minutes/hours to this DateTime.
We then take this new run time and subtract DateTime.Now from this DateTime, leaving us with the timespan untill the next run.
How ever, what if the current time is 01:50 on a daylightsavings day, we add 20 minutes, which is our set interval, and end up with a time of 02:10, how ever since this is daylightsavinds, it's actually 01:10.
When i subtract the current time (01:50) from the 01:10 (which is actually 02:10) does this return a negative value which i need to work around or does this never ever return a negative value because DateTime is just a long underneath holding the proper information?
Basically, the following code, is the check needed or not?
//Get interval between nextrun and right now!
double interval = (NextRun - DateTime.Now).TotalMilliseconds;
//Check if interval is ever less or equal to 0, should never happen but maybe with daylight saving time?
if(interval <= 0)
{
//Set default value
interval = IntervalInMilliseconds;
}
We believe that this check isn't needed but our googling so far hasn't given us a definative answer.
Use DateTime.UtcNow instead of DateTime.Now EVERYWHERE
First of all, you can try it yourself as it will help you understand how it works.
Essentially, using your example above, if you have 20 minutes to a local time, it would be 2:10 and not 1:10 as the computation is done in local time. If you want to get 1:10, you need to convert local time to universal time, add 20 minutes and then convert back to local time.
If you want real elapsed time, then you have to convert time to universal time before computing time difference. Also, if you work in local time, you won't be able to differentiate ambiguous time when the clock goes back.
In C++ I am able to get the current time when my application starts I can use
time_t appStartTime = time(null);
then to find the difference in seconds from when it started I can just do the same thing, then find the difference. It looks like I should be using "System.DateTime" in C# net, but the MSDN is confusing in its explanation.
How can I use System.DateTime to find the difference in time (in seconds) between when my application starts, and the current time?
Use Now property
DateTime startTime = DateTime.Now;
//work
DateTime currentTime = DateTime.Now;
and then just simply calculate the difference.
currentTime - startTime;
If you would like to measure the performance consider using Stopwatch.
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//work
stopWatch.Stop();
As everyone suggested... But they were a little wrong :-) Use DateTime.UtcNow, because
It's faster (DateTime.Now calls DateTime.UtcNow)
It works around change of DST on/off.
OR
As #Shekhar_Pro suggested (yes, he was right!), use the Stopwatch
var sw = Stopwatch.StartNew()
.... your code
sw.Stop();
var ms = sw.ElapsedMilliseconds;
or
var ticks = sw.ElapsedTicks;
Oh... and I was forgetting... What you are doing is probably worthless in certain situation... You know, 2011 processors are multicore (and even 2010 :-) )... If you app is vaguely multithread you are probably better measuring:
Process.GetCurrentProcess().TotalProcessorTime
This include the use of all the cores used by your app... So on a dual core, using both cores, it will "gain" 2 seconds for every "real time" second.
If you are using this for checking performance and time taken to Execute code then you Best bet is to use StopWatch.
otherwise System.DateTime has a Subtract function which can be used to get a TimeSpan object or even a simple - (subtract) operator will do it.
Then that TimeSpan object has a property of TotalSeconds which you can use.
Several ways to do this:
Use DateTime.Now. Subtracting produces a TimeSpan. Takes 8 bytes of storage, times up to 8000 years, resolution of 1 millisecond but accurate to 1/64 second on most machines.
Use Environment.TickCount. Similar to time_t but relative from machine boot time. Takes 4 bytes of storage, times up to 24 days (49 with a cast), resolution and accuracy same as DateTime.
Use Stopwatch. Stored on the heap, resolution is machine dependent but almost always well below a microsecond. Accuracy isn't usually good but repeats decently, assume +/- 5%. Best used to measure small intervals for comparison.
Use timeGetTime. This requires pinvoke to use this multimedia timer. Similar to Environment.TickCount, you can get 1 msec accuracy by using timeBeginPeriod. This is not cheap since it has system-wide effects. Best avoided.
Keep in mind that process execution is subject to the vagaries of overall operating system load, your program is sharing resources with the other 70-odd processes that are running. Either DateTime or TickCount has plenty of accuracy for that.
DateTime startTime = DateTime.Now;
//some code
TimeSpan difference = DateTime.Now - startTime;
int seconds = difference.TotalSeconds.Truncate();
I have code running in a loop and it's saving state based on the current time. Sometimes this can be just milliseconds apart, but for some reason it seems that DateTime.Now will always return values of at least 10 ms apart even if it's only 2 or 3 ms later. This presents a major problem since the state i'm saving depends on the time it was saved (e.g. recording something)
My test code that returns each value 10 ms apart:
public static void Main()
{
var dt1 = DateTime.Now;
System.Threading.Thread.Sleep(2);
var dt2 = DateTime.Now;
// On my machine the values will be at least 10 ms apart
Console.WriteLine("First: {0}, Second: {1}", dt1.Millisecond, dt2.Millisecond);
}
Is there another solution on how to get the accurate current time up to the millisecond ?
Someone suggested to look at the Stopwatch class. Although the Stopwatch class is very accurate it does not tell me the current time, something i need in order to save the state of my program.
Curiously, your code works perfectly fine on my quad core under Win7, generating values exactly 2 ms apart almost every time.
So I've done a more thorough test. Here's my example output for Thread.Sleep(1). The code prints the number of ms between consecutive calls to DateTime.UtcNow in a loop:
Each row contains 100 characters, and thus represents 100ms of time on a "clean run". So this screen covers roughly 2 seconds. The longest preemption was 4ms; moreover, there was a period lasting around 1 second when every iteration took exactly 1 ms. That's almost real-time OS quality!1 :)
So I tried again, with Thread.Sleep(2) this time:
Again, almost perfect results. This time each row is 200ms long, and there's a run almost 3 seconds long where the gap was never anything other than exactly 2ms.
Naturally, the next thing to see is the actual resolution of DateTime.UtcNow on my machine. Here's a run with no sleeping at all; a . is printed if UtcNow didn't change at all:
Finally, while investigating a strange case of timestamps being 15ms apart on the same machine that produced the above results, I've run into the following curious occurrences:
There is a function in the Windows API called timeBeginPeriod, which applications can use to temporarily increase the timer frequency, so this is presumably what happened here. Detailed documentation of the timer resolution is available via the Hardware Dev Center Archive, specifically Timer-Resolution.docx (a Word file).
Conclusions:
DateTime.UtcNow can have a much higher resolution than 15ms
Thread.Sleep(1) can sleep for exactly 1ms
On my machine, UtcNow grows grow by exactly 1ms at a time (give or take a rounding error - Reflector shows that there's a division in UtcNow).
It is possible for the process to switch into a low-res mode, when everything is 15.6ms-based, and a high-res mode, with 1ms slices, on the fly.
Here's the code:
static void Main(string[] args)
{
Console.BufferWidth = Console.WindowWidth = 100;
Console.WindowHeight = 20;
long lastticks = 0;
while (true)
{
long diff = DateTime.UtcNow.Ticks - lastticks;
if (diff == 0)
Console.Write(".");
else
switch (diff)
{
case 10000: case 10001: case 10002: Console.ForegroundColor=ConsoleColor.Red; Console.Write("1"); break;
case 20000: case 20001: case 20002: Console.ForegroundColor=ConsoleColor.Green; Console.Write("2"); break;
case 30000: case 30001: case 30002: Console.ForegroundColor=ConsoleColor.Yellow; Console.Write("3"); break;
default: Console.Write("[{0:0.###}]", diff / 10000.0); break;
}
Console.ForegroundColor = ConsoleColor.Gray;
lastticks += diff;
}
}
It turns out there exists an undocumented function which can alter the timer resolution. I haven't investigated the details, but I thought I'd post a link here: NtSetTimerResolution.
1Of course I made extra certain that the OS was as idle as possible, and there are four fairly powerful CPU cores at its disposal. If I load all four cores to 100% the picture changes completely, with long preemptions everywhere.
The problem with DateTime when dealing with milliseconds isn't due to the DateTime class at all, but rather, has to do with CPU ticks and thread slices. Essentially, when an operation is paused by the scheduler to allow other threads to execute, it must wait at a minimum of 1 time slice before resuming which is around 15ms on modern Windows OSes. Therefore, any attempt to pause for less than this 15ms precision will lead to unexpected results.
IF you take a snap shot of the current time before you do anything, you can just add the stopwatch to the time you stored, no?
You should ask yourself if you really need accurate time, or just close enough time plus an increasing integer.
You can do good things by getting now() just after a wait event such as a mutex, select, poll, WaitFor*, etc, and then adding a serial number to that, perhaps in the nanosecond range or wherever there is room.
You can also use the rdtsc machine instruction (some libraries provide an API wrapper for this, not sure about doing this in C# or Java) to get cheap time from the CPU and combine that with time from now(). The problem with rdtsc is that on systems with speed scaling you can never be quite sure what its going to do. It also wraps around fairly quickly.
All that I used to accomplish this task 100% accurately is a timer control, and a label.
The code does not require much explanation, fairly simple.
Global Variables:
int timer = 0;
This is the tick event:
private void timeOfDay_Tick(object sender, EventArgs e)
{
timeOfDay.Enabled = false;
timer++;
if (timer <= 1)
{
timeOfDay.Interval = 1000;
timeOfDay.Enabled = true;
lblTime.Text = "Time: " + DateTime.Now.ToString("h:mm:ss tt");
timer = 0;
}
}
Here is the form load:
private void DriverAssignment_Load(object sender, EventArgs e)
{
timeOfDay.Interval= 1;
timeOfDay.Enabled = true;
}
Answering the second part of your question regarding a more precise API, the comment from AnotherUser lead me to this solution that in my scenario overcomes the DateTime.Now precision issue:
static FileTime time;
public static DateTime Now()
{
GetSystemTimePreciseAsFileTime(out time);
var newTime = (ulong)time.dwHighDateTime << (8 * 4) | time.dwLowDateTime;
var newTimeSigned = Convert.ToInt64(newTime);
return new DateTime(newTimeSigned).AddYears(1600).ToLocalTime();
}
public struct FileTime
{
public uint dwLowDateTime;
public uint dwHighDateTime;
}
[DllImport("Kernel32.dll")]
public static extern void GetSystemTimePreciseAsFileTime(out FileTime lpSystemTimeAsFileTime);
In my own benchmarks, iterating 1M, it returns on an average 3 ticks vs DateTime.Now 2 ticks.
Why 1600 is out of my jurisdiction, but I use it to get the correct year.
EDIT: This is still an issue on win10. Anybody interested can run this peace of evidence:
void Main()
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(Now().ToString("yyyy-MM-dd HH:mm:ss.fffffff"));
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffffff"));
Console.WriteLine();
}
}
// include the code above
You could use DateTime.Now.Ticks, read the artical on MSDN
"A single tick represents one hundred nanoseconds or one ten-millionth of a second."