Low Latency Best Practices
There are several tips to achieve minimum latency.
- Configure process priority and affinity.
- Receive Spinning Timeout.
- Turn off logging.
Configure process priority and affinity
To achieve minimum latency process priority of using application, Handler should be set to High or even Realtime.
The Handler uses several threads, that's why the application should not be limited to the single processor core.
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;
//Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2); // If this line will be uncommented, apllication will be limited to second processor core only.
Configure receiving thread priority and affinity
To achieve minimum latency thread priority of using application, Handler should be set to Highest.
The Handler uses several threads, that's why the application should not be limited to the single processor core.
handler.ReceivingThreadPriority = System.Threading.ThreadPriority.Highest;
handler.ReceivingThreadAffinity = new uint[] { 2, 3 }; // Limit Handler to 2 and 3 cores.
Receive Spinning Timeout
ReceiveSpinningTimeout property can be used to decrease the latency of the data receiving. If the value is zero (by default), the receiving thread will wait for a new packet in the blocking wait mode. If the value greater than zero, the receiving thread will wait for a new packet in the spin loop mode before switching to the blocking wait mode.
The property specifies the spin loop period in microseconds.
ReceiveSpinningTimeout property using makes sense when your handler receives packets frequently - in this case, waiting in the loop is cheaper than the thread context switch to the blocking wait mode. However please note that the spin wait increases the CPU usage so the spin wait period should not be too long.
handler.ReceiveSpinningTimeout = 200000; // Microseconds
Turn off logging
When NLog-based logging is used, all loggers should be turned off via NLog.config file or programmatically.