Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime drifting - weird issue after 2 hours

Tags:

c#

.net

timing

I have a thread to generate a network packet every 40 ms (25 Hz), it's an infinite loop (until told to stop), and I'm using thread.sleep.

When I build the packet, one of the values is the current GPS time, using DateTime.UtcNow and adding the leap seconds.

This works fine when I start, but it drifts with time, about 2 hours later, it's 5 seconds behind.

I have a Symmetrom GPS Time Server and I'm using their software as the NTP client, and it says the cumulative drift on the PC is about 1.2 seconds (most of that I've noticed is drift while the PC is off and not syncing to NTP).

Anyone have any idea whats going wrong? I know thread.sleep isn't perfect timing, and Windows isn't an RTOS, but the drift doesn't make sense, dropping frames would.

I can't post code due to some proprietary and ITAR issues, but I can post a rough outline:

while(!abort) { 
   currentTime = DateTime.UtcNow + leapSeconds ; 
   buildPacket(currentTime); 
   stream.Write(msg, 0, sendSize); 
   //NetworkStream Thread.Sleep(40); 
}

I'm in Windows 7 and using Visual Studios 2010.

like image 939
Mike D Avatar asked Jan 13 '14 20:01

Mike D


1 Answers

I think this happens because the time that a while loop executes is 40 ms (your sleep) + the time necessary to execute the code that builds the packet.

Have you tried using a System.Threading.Timer ? This way your code will execute in a separate thread then the one that is counting your time. However, I don't think the performance is good enough to keep your real time application running for long.

like image 155
Cosmin Vană Avatar answered Oct 03 '22 10:10

Cosmin Vană