Solution for inaccurate timers

Use high-precision hardware clocks to achieve nanosecond-level accuracy, bypassing the limitations of system clock resolution.

Windows 10: The default system clock resolution is 15.625ms (64Hz). Task.Delay(1) is aligned to the nearest clock tick, resulting in an actual delay of ~12-15ms (test data: 13.0369ms, 14.4563ms).

Android: Timer resolution is typically 10-20ms (depending on device and system version). Task.Delay(1) may result in a delay of 10-20ms, affected by power optimizations (e.g., Doze mode).

To achieve higher precision, use the hardware clock: Stopwatch.GetTimestamp and GetElapsedTime use the hardware clock (nanosecond-level precision).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
await Task.Run(async() => 
{
    int k = 0;
    int n = 100;
    int m = 60;
    int millisecond = 5;

    var _stopwatch = Stopwatch.StartNew();
    for (int i = 0; i < 200 * 60; i++)
    {
        var start = Stopwatch.GetTimestamp();
        while (Stopwatch.GetElapsedTime(start).TotalMilliseconds < millisecond)
        {
            Thread.SpinWait(10);
        }
        _dataPoints.Add(m_dataPoints[k++]);
    }
    _stopwatch?.Stop();
    await Task.Delay(100);
    Debug.WriteLine($"Total: {_stopwatch.Elapsed.TotalSeconds}");
});
Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy