Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I speed up Java DatagramSocket performance?

Tags:

java

sockets

I'm using Java DatagramSocket class to send a UDP data gram to an endpoint. The datagram must arrive at the endpoint in 60ms intervals.

I'm finding that DatagramSocket.Send can often take > 1 ms (close to 2) to package and send packets no greater than 56 bytes. This causes my packets to be delivered at 62 ms intervals, rather than 60ms intervals.

This is on a windows vista machine. Here is how I'm measuring the time:

              DatagramPacket d = new DatagramPacket(out, out.length, address, port);
              long nanoTime = System.nanoTime();
    socket.send(d);
    long diff = System.nanoTime() - nanoTime;
    System.out.println( out.length + " in " + diff + "ms." );

Does any one have tips or tricks to speed this process?

like image 572
LPalmer Avatar asked Dec 10 '22 20:12

LPalmer


2 Answers

You can use the Timer class to schedule an event.

    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        public void run() {
            //send packet here
        }};
    timer.scheduleAtFixedRate(task, 0, 60);

This will create a recurring event every 60ms to execute the "run" command. All things remaining equal, the packet should hit the wire every 60ms (although, the first packet will be delayed by some amount, and garbage collection/other tasks/etc may slightly delay this number).

like image 109
James Van Huis Avatar answered Dec 24 '22 02:12

James Van Huis


You're seeing the time taken to copy the data from user-space into kernel space. It takes even longer to send through the UDP, IP and Ethernet layers and it can take a variable amount of time for a datagram to cross the physical network to its destination.

Assuming you have a network that exhibits no jitter (variance in per-packet transmission time) and your process is running at real-time priority, and nothing else is competing with it for the CPU...

You need to call send every 60ms, no matter how long it takes for the send() method to execute. You cannot wait 60ms between calls. You need to measure how long it takes to perform the body of your loop (send() and whatever else) and subtract that from 60ms to get the wait time.

like image 40
Nat Avatar answered Dec 24 '22 04:12

Nat