in reply to I know two prints are slower than one, but 200x slower?!?!?

I think you're getting Nagled. From the wikipedia article: "With both algorithms enabled, applications which do two successive writes to a TCP connection, followed by a read, experience a constant delay of up to 500 milliseconds, the 'ACK delay'."

Adding setsockopt($sock, IPPROTO_TCP, TCP_NODELAY, 1); just after your accept seems to clear the delay in the two print case, confirming the guess.

Of course, this now raises two other questions:

  1. Why does closing the socket in the parent make a difference?
  2. Why doesn't this trigger on windows (which surely has these basic TCP algorithms enabled by default too?)

Replies are listed 'Best First'.
Re^2: I know two prints are slower than one, but 200x slower?!?!?
by cdarke (Prior) on Aug 16, 2007 at 11:03 UTC
    The thing about the Nagle argorithm is that you can get wildly different results depending on the activity on the network. Perservsly a quiet network can give worse performance figures, since tehre are no extra packets for the ACK to piggy-back.
    BTW, the Nagle argorithm is there to reduce collisions, so be careful of using TCP_NODELAY - that will make a bad network worse.
      Exactly right.

      Candidates for turning off Nagle's Algorithm are applications which will create a trickle of a few small packets on a probably-quiet network, and yet should still be pretty low latency.

      For example, a user who is typing would find it really annoying to suffer lag on full-duplex telnet. They can't see what they typed until the character is echoed back.

      If your packets are big (multiple hundreds of bytes), if variable latency isn't a problem, or you are spewing many many packets to keep the network saturated much of the time, then let Nagle do its job.

      In the 90s (and still today), tons of games developers would think that they needed to reinvent all the "promises" of TCP by writing a huge and ugly app layer on top of a UDP datagrams protocol. It's folly to reinvent TCP at the app layer, especially when all the infrastructure is highly tuned to do TCP really really well. Turning off Nagle usually opened their eyes in disbelief.

      --
      [ e d @ h a l l e y . c c ]