Ruby Nest Features

I make send / recv repeated calls on TCP sockets in Ruby and found significant speed differences between the two uses of the sockets --- just put, reusing the socket proves slower than constantly closing and reopening.

Server in this way:

s = TCPServer.new( 4545 ) while( c = s.accept ) while( m = c.gets ) c.puts( m.chomp ) end end s.close 

It simply repeats the request to the client.

Client 1 is rebuilt each time:

 t1 = Time.now 1000.times{ s = TCPSocket.new( '127.0.0.1', 4545 ) s.puts( 'test' ) s.gets s.close } puts "Reconnecting: #{Time.now - t1}s" 

Client 2 opens his outlet:

 t1 = Time.now s = TCPSocket.new( '127.0.0.1', 4545 ) s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) #Nagle 1000.times{ s.puts( 'test' ) s.gets } s.close puts "Persistent: #{Time.now - t1}s" 

The result of running this code is as follows:

 % ruby test_client.rb Reconnecting: 0.233751849s Persistent (w/Nagle): 79.925120196s Persistent (NODELAY): 39.958955967s 

I understand that reusing a socket should save me time (and not 347 times more!). I tried calling IO#flush after writing to sockets, but that doesn't matter. Disabling the Nagle algorithm helps to some extent, but nowhere is enough.

What can lead to the fact that the above code (running on Linux 3.8.5 and ruby ​​2.0.0) will be executed with such a big discrepancy in speed and how can I fix it?

+8
performance ruby sockets tcp
source share
1 answer

Disabling the Nagle algorithm on both client and server sockets eliminates this:

 s = TCPServer.new( 4545 ) while( c = s.accept ) c.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) while( m = c.gets ) c.puts( m.chomp ) end end s.close 

Result:

 % ruby test_client.rb Reconnect: 0.189858182s Persistent: 0.030973398s 

Hope this helps someone.

+7
source share

All Articles