Unexpected random behavior of Task.Delay in unit test [duplicate] - c#

I just ran into some unexpected behavior with DateTime.UtcNow while doing some unit tests. It appears that when you call DateTime.Now/UtcNow in rapid succession, it seems to give you back the same value for a longer-than-expected interval of time, rather than capturing more precise millisecond increments.
I know there is a Stopwatch class that would be better suited for doing precise time measurements, but I was curious if someone could explain this behavior in DateTime? Is there an official precision documented for DateTime.Now (for example, precise to within 50 ms?)? Why would DateTime.Now be made less precise than what most CPU clocks could handle? Maybe it's just designed for the lowest common denominator CPU?
public static void Main(string[] args)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
for (int i=0; i<1000; i++)
{
var now = DateTime.Now;
Console.WriteLine(string.Format(
"Ticks: {0}\tMilliseconds: {1}", now.Ticks, now.Millisecond));
}
stopwatch.Stop();
Console.WriteLine("Stopwatch.ElapsedMilliseconds: {0}",
stopwatch.ElapsedMilliseconds);
Console.ReadLine();
}

Why would DateTime.Now be made less precise than what most CPU clocks could handle?
A good clock should be both precise and accurate; those are different. As the old joke goes, a stopped clock is exactly accurate twice a day, a clock a minute slow is never accurate at any time. But the clock a minute slow is always precise to the nearest minute, whereas a stopped clock has no useful precision at all.
Why should the DateTime be precise to, say a microsecond when it cannot possibly be accurate to the microsecond? Most people do not have any source for official time signals that are accurate to the microsecond. Therefore giving six digits after the decimal place of precision, the last five of which are garbage would be lying.
Remember, the purpose of DateTime is to represent a date and time. High-precision timings is not at all the purpose of DateTime; as you note, that's the purpose of StopWatch. The purpose of DateTime is to represent a date and time for purposes like displaying the current time to the user, computing the number of days until next Tuesday, and so on.
In short, "what time is it?" and "how long did that take?" are completely different questions; don't use a tool designed to answer one question to answer the other.
Thanks for the question; this will make a good blog article! :-)

DateTime's precision is somewhat specific to the system it's being run on. The precision is related to the speed of a context switch, which tends to be around 15 or 16 ms. (On my system, it is actually about 14 ms from my testing, but I've seen some laptops where it's closer to 35-40 ms accuracy.)
Peter Bromberg wrote an article on high precision code timing in C#, which discusses this.

I would like a precise Datetime.Now :), so I cooked this up:
public class PreciseDatetime
{
// using DateTime.Now resulted in many many log events with the same timestamp.
// use static variables in case there are many instances of this class in use in the same program
// (that way they will all be in sync)
private static readonly Stopwatch myStopwatch = new Stopwatch();
private static System.DateTime myStopwatchStartTime;
static PreciseDatetime()
{
Reset();
try
{
// In case the system clock gets updated
SystemEvents.TimeChanged += SystemEvents_TimeChanged;
}
catch (Exception)
{
}
}
static void SystemEvents_TimeChanged(object sender, EventArgs e)
{
Reset();
}
// SystemEvents.TimeChanged can be slow to fire (3 secs), so allow forcing of reset
static public void Reset()
{
myStopwatchStartTime = System.DateTime.Now;
myStopwatch.Restart();
}
public System.DateTime Now { get { return myStopwatchStartTime.Add(myStopwatch.Elapsed); } }
}

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. Better precision can be obtained using QueryPerformanceCounter.

For what it's worth, short of actually checking the .NET source, Eric Lippert provided a comment on this SO question saying that DateTime is only accurate to approx 30 ms. The reasoning for not being nanosecond accurate, in his words, is that it "doesn't need to be."

From MSDN documentation:
The resolution of this property
depends on the system timer.
They also claim that the approximate resolution on Windows NT 3.5 and later is 10 ms :)

The resolution of this property depends on the system timer, which
depends on the underlying operating system. It tends to be between 0.5
and 15 milliseconds.
As a result, repeated calls to the Now property in a short time interval, such as in a loop, may return the same value.
MSDN Link

Related

Using Stopwatch timer versus DateTime comparisons every 1 second?

Imagine we have a dedicated OS thread, that must do something every 4.30 minutes.
You cannot suspend the thread, because it needs to check/do other things, nor can you use await/async, because that would cause the command to drop out of the dedicated OS thread, defeating the purpose of first creating one.
To solve the problem above, I found 2 solutions:
Use System.Diagnostics.Stopwatch to start a new Stopwatch object, and compare it every 1 second if it reached the desired time-frame: if (timer.ElapsedMilliseconds == 258000) { ...}
Use System.DateTime to initialize a DateTime object DateTime.UtcNow.AddMinutes(4.30) and compare that to the current date every 1 second: if (DateTime.UtcNow >= initializedDate) { ... }
First approach uses a Stopwatch. I think the Stopwatch uses a thread to do all the work, which is why I wanted to avoid it?
The second approach uses a lot of DateTime objects. Every 1 second we'd be constructing a new DateTime object of the current date.
The two solutions are equivalent unless you want very high precision: Stopwatch will use a high precision system timer if available and falls back to DateTime if not. To address your concerns:
Stopwatch does NOT use a separate thread. It just reads the system ticks (high or low precision) and does some math for you.
DateTime is a struct so creating a new instance every second should be cheap and put zero pressure on the GC.
I'd use the Stopwatch because it gives me the elapsed time for free. :)

Get milliseconds passed

A just need a stable count of the current program's progression in milliseconds in C#. I don't care about what timestamp it goes off of, whether it's when the program starts, midnight, or the epoch, I just need a single function that returns a stable millisecond value that does not change in an abnormal manner besides increasing by 1 each millisecond. You'd be surprised how few comprehensive and simple answers I could find by searching.
Edit: Why did you remove the C# from my title? I'd figure that's a pretty important piece of information.
When your program starts create a StopWatch and Start() it.
private StopWatch sw = new StopWatch();
public void StartMethod()
{
sw.Start();
}
At any point you can query the Stopwatch:
public void SomeMethod()
{
var a = sw.ElapsedMilliseconds;
}
If you want something accurate/precise then you need to use a StopWatch, and please read Eric Lippert's Blog (formerly the Principal Developer of the C# compiler Team) Precision and accuracy of DateTime.
Excerpt:
Now, the question “how much time has elapsed from start to finish?” is a completely different question than “what time is it right now?” If the question you want to ask is about how long some operation took, and you want a high-precision, high-accuracy answer, then use the StopWatch class. It really does have nanosecond precision and accuracy that is close to its precision.
If you don't need an accurate time, and you don't care about precision and the possibility of edge-cases that cause your milliseconds to actually be negative then use DateTime.
Do you mean DateTime.Now? It holds absolute time, and subtracting two DateTime instances gives you a TimeSpan object which has a TotalMilliseconds property.
You could store the current time in milliseconds when the program starts, then in your function get the current time again and subtract
edit:
if what your going for is a stable count of process cycles, I would use processor clocks instead of time.
as per your comment you can use DateTime.Ticks, which is 1/10,000 of a millisecond per tick
Also, if you wanted to do the time thing you can use DateTime.Now as your variable you store when you start your program, and do another DateTime.Now whenever you want the time. It has a millisecond property.
Either way DateTime is what your looking for
It sounds like you are just trying to get the current date and time, in milliseconds. If you are just trying to get the current time, in milliseconds, try this:
long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;

Elapsed time from start to finish with 20 ms precision

From this article http://blogs.msdn.com/b/ericlippert/archive/2010/04/08/precision-and-accuracy-of-datetime.aspx:
Now, the question “how much time has elapsed from start to finish?” is a completely different question than “what time is it right now?” If the question you want to ask is about how long some operation took, and you want a high-precision, high-accuracy answer, then use the StopWatch class. It really does have nanosecond precision and accuracy that is close to its precision.
The question is - what should I use if I need elapsed time from start to finish and I need 20 ms precision?
StopWatch has much better precision so I'm afraid that I will pay processor time for "extra-precision" which I don't need.
DateTime.Now has exactly precision I need but it also has a lot of extra-stuff like Month, Year etc. and I'm again afraid that this makes it much slower.
This article should help you:
http://www.dijksterhuis.org/timing-function-performance-stopwatch-class/
In general it says that the Stopwatch is the better choice, which is even my personal opinion.
The only (considerable?) overhead of the StopWatch is the incorporation of QueryPerformanceFrequency determining if the StopWatch will go on with high resolution frequency or not. Actually it is an overhead only if it will go without high resolution frequency. Otherwise is a faster option as it gets the timestamp with a WIN32 QueryPerformanceCounter call instead of DateTime.UtcNow.Ticks.
From what I read on the internet untill now StopWatch class from System.Diagnostics namespace is the best class used for timing.
If you want precision under 1 ms remember to use the Elapsed.TotalMilliseconds property to retrieve elapsed time, sw.ElapsedMilliseconds jumps in increments of 1 ms.
using System;
using System.Diagnostics;
namespace MySolution
{
class Program
{
static void Main(string[] args)
{
var sw = Stopwatch.StartNew();
// code to be timed here
sw.Stop();
Console.WriteLine("Run time in ms = {0}", sw.Elapsed.TotalMilliseconds);
}
}
}

More precise Thread.Sleep

How can i do Thread.Sleep(10.4166667);?
OK i see now that Sleep is not the way to go.
So i use Timer but timer is also in ms put i need more precise
Is there timer with nanosecond accuracy?
So you want your thread to sleep precisely for that time and then resume? Forget about it. This parameter tells the system to wake the Thread after at least this number of milliseconds. At least. And after resuming, the thread could be put to sleep once again in a blink of an eye. That just how Operating Systems work and you cannot control it.
Please note that Thread.Sleep sleeps as long as you tell it (not even precisely), no matter how long code before or after takes to execute.
Your question seems to imply that you want some code to be executed in certain intervals, since a precise time seems to matter. Thus you might prefer a Timer.
To do such a precise sleep you would need to use a real time operating system and you would likely need specialized hardware. Integrity RTOS claims to respond to interrupts in nanoseconds, as do others.
This isn't going to happen with C# or any kind of high level sleep call.
Please note that the argument is in milliseconds, so 10 is 10 milliseconds. Are you sure you want 10.41 etc milliseconds? If you want 10.41 seconds, then you can use 10416.
The input to Thread.Sleep is the number of milliseconds for which the thread is blocked. After that it will be runnable, but you have no influence over when it is actually scheduled. I.e. in theory the thread could wait forever before resuming execution.
It hardly ever makes sense to rely on specific number of milliseconds here. If you're trying to synchronize work between two threads there are better options than using Sleep.
As you already mentioned: You could combine DispatcherTimer with Stopwatch (Making sure the IsHighResolution and Frequency suits your needs). Start the Timer and the Stopwatch, and on discreet Ticks of the Timer check the exact elapsed time of the stopwatch.
If you are trying to rate-limit a calculation and insist on using only Thread.Sleep then be aware there is a an underlying kernel pulse rate (roughly 15ms), so your thread will only resume when a pulse occurs. The guarantee provided is to "wait at least the specified duration." For example, if you call Thread.Sleep(1) (to wait 1ms), and the last pulse was 13ms ago, then you will end up waiting 2ms until the next pulse comes.
The draw synchronization I implemented for a rendering engine does something similar to dithering to get the quantization to the 15ms intervals to be uniformly distributed around my desired time interval. It is mostly just a matter of subtracting half the pulse interval from the sleep duration, so only half the invocations wait the extra duration to the next 15ms pulse, and half occur early.
public class TimeSynchronizer {
//see https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep
public const double THREAD_PULSE_MS = 15.6d;//TODO read exact value for your system
public readonly TimeSpan Min = TimeSpan.Zero;
public TimeSynchronizer(TimeSpan? min = null) {
if (min.HasValue && min.Value.Ticks > 0L) this.Min = min.Value;
}
private DateTime _targetTimeUtc = DateTime.UtcNow;//you may wish to defer this initialization so the first Synchronize() call assuredly doesn't wait
public void Synchronize() {
if (this.Min.Ticks > 0L) {
DateTime nowUtc = DateTime.UtcNow;
TimeSpan waitDuration = this._targetTimeUtc - nowUtc;
//store the exact desired return time for the next inerval
if (waitDuration.Ticks > 0L)
this._targetTimeUtc += this.Min;
else this._targetTimeUtc = nowUtc + this.Min;//missed it (this does not preserve absolute synchronization and can de-phase from metered interval times)
if (waitDuration.TotalMilliseconds > THREAD_PULSE_MS/2d)
Thread.Sleep(waitDuration.Subtract(TimeSpan.FromMilliseconds(THREAD_PULSE_MS/2d)));
}
}
}
I do not recommend this solution if your nominal sleep durations are significantly less than the pulse rate, because it will frequently not wait at all in that case.
The following screenshot shows rough percentile bands on how long it truly takes (from buckets of 20 samples each - dark green are the median values), with a (nominal) minimum duration between frames set at 30fps (33.333ms):
I am suspicious that the exact pulse duration is 1 second / 600, since in SQL server a single DateTime tick is exactly 1/300th of a second

how to get a real time clock in C#?

i want a real time clock with precision of microseconds how can i do so?
is there any real time clock other than stopwatch;
You want System.Diagnostics.Stopwatch, which can measure time intervals accurately to the microsecond (depending on hardware limitations).
System.Diagnostics.Stopwatch uses the QueryPerformanceCounter and QueryPerformanceFrequency Windows APIs. The resolution is not standard across machines, but generally it's on the order of microseconds (see this KB article for more info).
In Vista/Win7 there is also QueryProcessCycleTime and QueryThreadCycleTime which will give you the number of elapsed cycles for your process/thread. This is useful if you want to know only the active time for the process (e.g. time when you weren't switched-out).
The most precise timer available in .NET is StopWatch.
For a high resolution measurements you could use the QueryPerformanceCounter function:
class Program
{
[DllImport("kernel32.dll")]
private static extern void QueryPerformanceCounter(ref long ticks);
static void Main()
{
long startTicks = 0L;
QueryPerformanceCounter(ref startTicks);
// some task
long endTicks = 0L;
QueryPerformanceCounter(ref endTicks);
long res = endTicks - startTicks;
}
}
check this http://www.c-sharpcorner.com/UploadFile/kapilsoni88/Digital_Click08142008142713PM/Digital_Click.aspx
and also check this http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
If you want a good time mesurement I think csharp as an high level language might not be a good idea. you could assemble a simple program that taps to RTC and then tie it to your program via a library. That is literally the best possible scenario you can get whith no Object overhang, but it requires some low level know how to put together.
If you have no internet access and you want real time for timed trial license of software then you can use USB dongle with Real time clock.
Its time calculation is driven by an internal clock which is battery-driven. You can access the time from USB dongle using API functions which come along with these types of dongles.
EX-http://www.senselock-europe.com/en/elite-el-rtc-dongle.html

Categories

Resources