views:

579

answers:

1

I have this simple piece of code that writes to a socket, then reads the response from the server. The server is very fast (responds within 5ms every time). However, while writing to the socket is quick -- reading the response from the socket is always MUCH slower. Any clues?

module UriTester
  module UriInfo
    class << self
      def send_receive(socket, xml)
#        socket = TCPSocket.open("service.server.com","2316")
        begin
        start = Time.now
          socket.print(xml)           # Send request
        puts "just printed the xml into socket #{Time.now - start}"
        rescue Errno::ECONNRESET
        puts "looks like there is an issue!!!"
          socket = TCPSocket.open("service.server.com","2316")
          socket.print(xml)           # Send request
        end
        response=""
        while (line =socket.recv(1024))
          response += line
          break unless line.grep(/<\/bcap>/).empty?
        end
        puts "SEND_RECEIVE COMPLETED. IN #{Time.now - start}"
#        socket.close
        response
      end
    end
  end
end

Thanks!

+4  A: 

Writing to the socket will always be way faster than reading in this case because the write is local to the machine and the read has to wait for a response to come over the network.

In more detail, when the call to write / send returns all the system is telling you is that N bytes have been successfully copied to the sockets kernel space buffer. It does not mean that the data has actually been sent across the network yet. In fact, the data can sit in the socket buffer for quite a long time ( assuming you're using TCP ). This is because of something called the Nagle algorithm which is intended to make efficient use of network bandwidth. This unseen Nagle delay adds to the round trip time and how long till you get a response. The server might also delay it's response for the same reason adding even more to the response time.

So when you time the write and it returns quickly, that doesn't actually mean anything useful.

As mentioned earlier the read from the socket will be way longer since when you time the read you are actually timing the round trip travel time plus server response time, which is always going to be way slower than the time it takes to copy data from a user space program to a kernel buffer.

What is it that you are actually trying to measure and why?

Robert S. Barnes