high frequency timing .NET

前端 未结 4 1458
猫巷女王i
猫巷女王i 2020-12-03 06:19

I\'m looking to create a high frequency callback thread. Essentially I need a function to execute at a regular high frequency (up to 100Hz) interval. I realize that windows

4条回答
  •  长情又很酷
    2020-12-03 06:37

    Thread.Sleep() does not seem to be as inaccurate as you may think at such small intervals, The following on Windows 8.1 x64 i7 Laptop .NET 4.0:

    using System;
    using System.Diagnostics;
    using System.Threading;
    
    namespace HighFrequency
    {
        class Program
        {
            static void Main(string[] args)
            {
                var count = 0;
                var stopwatch = new Stopwatch();
                stopwatch.Start();
                while(count <= 1000)
                {
                    Thread.Sleep(1);
                    count++;
                }
                stopwatch.Stop();
                Console.WriteLine("C# .NET 4.0 avg. {0}", stopwatch.Elapsed.TotalSeconds / count);
            }
        }
    }
    

    Output:

    C# .NET 4.0 avg. 0.00197391928071928

    So just under 2ms interval! I guess if there was more contention that could rise pretty quickly, though I do have a number of apps open, just nothing grinding away.

    At sleeping for 10ms i.e. 100HZ, got an average of 0.0109... pretty much spot on!

提交回复
热议问题