high speed thread loop timing stability

ffb.boy.30

Member
Joined
Jan 18, 2017
Messages
5
Programming Experience
1-3
Hi,
I would like to make a thread loop to do calculations according time , like a PID.
For example If the loop run for 5sec and I make only a increment by one the output shoud be 5000 if my loop time is 1ms.
I've tried thread.sleep(1) in my thread loop but it is too slow, I've tried something like this
C#:
            UInt16 i = 0;

            DateTime _Start = DateTime.Now;
            DateTime _New = DateTime.Now;
            do
            {
                while ((DateTime.Now - _New)< TimeSpan.FromMilliseconds(1))  ;
                _New = DateTime.Now;

                i++;
                //Thread.Sleep(1);
            } while (i < 5000);
            TimeSpan _Span = DateTime.Now.Subtract(_Start);
            Console.WriteLine("dt {0}", _Span);

but not efficient too, it take 7.6sec to make 5000 loop

It is a winform application running on windows.

Thanks for your help
 
I answer to myself if someone need it

C#:
            UInt16 i = 0;

            Stopwatch _St = new Stopwatch();
            _St.Start();
            DateTime _Start = DateTime.Now;
            do
            {
                while (_St.ElapsedMilliseconds < 1)
                {
                    
                }
                _St.Restart();
                i++;
                //Thread.Sleep(1);
            } while (i < 5000);

            TimeSpan _Span = DateTime.Now.Subtract(_Start);
            Console.WriteLine("dt {0}", _Span.TotalMilliseconds);


And my 5000 loop duration is 5003,8292ms (y)
 
Never write code that does busy waiting. It's one the early things that CS students learn.
 
This "works" purely because a stopwatch uses a higher resolution timer than the clock that DateTime uses. Make a better job of waiting using a better timer and you won't need to write a loop that has your CPU doing nothing but looking at a stopwatch
 
Back
Top Bottom