MATLAB: How to improve UDP performance when using udp() function from Instrument Control Toolbox

datagramInstrument Control Toolboxudp

 I am using the fread() function to continuously receive datagrams, and the fprintf() function to write the data to a text file when a datagram is received:
UDP = udp(ip, port);UDP.InputBufferSize = 1024;
UDP.DatagramTerminateMode = 'ON';
fopen(UDP);
while 1
ADCdata = fread(UDP, 1, 'uint16');
fprintf(ADCdataFile, '%d\n', ADCdata);end
We would like the data rate to be as high as possible for our application. Right now, when transmitting at a rate of 4Mbps or so, the data is read in and saved with no problem. However, at 15–20Mbps, MATLAB is not able to keep up with the data, and much of the data is lost (i.e. not read/saved).
Is there a data rate limitation to the UDP fread() functionality that is known?
Is there a way to increase the rate at which UDP data is read in and saved to a file? Perhaps the above code is not optimal, or there may be a better function than fprintf()?

Best Answer

Regarding the usage for the 'udp' interface, the reading speed is slower than the data transmission most likely because the writing to file operation is happening for every byte. Please consider reading and processing the data in chunks to speed up the process.
Please refer to a modified example below that might help with your program by using callback function when a diagram packet is received, which should help speed things up:
UDP = udp(ip, port);
UDP.InputBufferSize = 1024;
UDP.DatagramTerminateMode = 'ON';
UDP.DatagramReceivedFcn = @callbackFcn; % the callbackFcn will be called whenever a UDP packet is received
fopen(UDP);
function callbackFcn(src, evt) % here the src is actually the udp object itself
fread(src, src.InputDatagramPacketSize, 'uint16');
% might need some modification for fprintf
end
Please note that it is not recommended to use UDP when transmitting heavy payloads because of the size limitation of the UDP itself.
In general, since UDP is established on top of IP (Internet Protocol), the theoretical maximum packet it can handle is 65,535 bytes including necessary headers. Packet larger than this is broken down by the protocol into separate packets and UDP does not guarantee the ordering and verification of delivery in this scenario.
However, it is not recommended to send a payload over 512 bytes in a single UDP packet, because smaller packets would most likely cause smaller issues in transmission as UDP is unreliable.
In MATLAB, according to this documentation page, the maximum packet size for reading is 8192 bytes. and you may write any data size to the output buffer but the data will be sent in packets of at most 4096 bytes.
Additional note: Starting from R2020b, the usage of udp() is no longer recommended. Use udpport() instead.