I am struggling with a timing issue I have in Docker
Here is my test code:
using System.Diagnostics;
DisplayStopWatchResolution();
var timer = new Stopwatch();
//begin the test
while (true)
{
timer.Restart();
timer.Start();
//Thread.Sleep(1);
await Task.Delay(1).ConfigureAwait(false);
timer.Stop();
Console.WriteLine($"Task time {timer.Elapsed.TotalMilliseconds}");
}
static void DisplayStopWatchResolution()
{
if (Stopwatch.IsHighResolution)
{
Console.WriteLine("Operations timed using the system's high-resolution performance counter.");
}
else
{
Console.WriteLine("Operations timed using the DateTime class.");
}
long frequency = Stopwatch.Frequency;
Console.WriteLine(" Timer frequency in ticks per second = {0}",
frequency);
long nanosecPerTick = (1000L * 1000L * 1000L) / frequency;
Console.WriteLine(" Timer is accurate within {0} nanoseconds",
nanosecPerTick);
}
What I want is for the system to wait around 1ms.
However I am getting these results:
-
Windows | Timer is accurate within 100 nanoseconds:
- await Task.Delay(1).ConfigureAwait(false); is roughly 1.942 ms (acceptable)
- Thread.Sleep(1) is again roughly 1.942ms (acceptable)
-
Linux (ubuntu on WSL using docker) | Timer is accurate within 1 nanoseconds:
- await Task.Delay(1).ConfigureAwait(false) is roughly 10 ms (my bad case)
- Thread.Sleep() is 1.0712ms (really good)
My preference for use would be Task.Delay() as to not block the thread however the performance is 10x what is should be.
My question is how to fix Task.Delay() under linux to not be so slow.
Thank you