title: Bad UDP performance in Golang vs. Python
body: <p>I want to send as many UDP packets as fast as possible. I tried different methods of sending UDP data in the <a href="https://golang.org/pkg/net/?m=all" rel="nofollow noreferrer">net</a> package, but ended up with the following;</p>
  <pre><code>func main() {
      for i := 0; i &lt; THREADS; i++ {
          go loopSendHello()
      }
  
      // Sleep forever
      &lt;-make(chan bool, 1)
  }
  
  func loopSendHello() {
      for {
          sendHello()
      }
  }
  
  func sendHello() {
      // Setup conn
      addr := net.UDPAddr{
          IP:   net.IP{192, 168, 1, xxx},
          Port: 1337,
      }
      conn, err := net.ListenPacket(&quot;udp&quot;, &quot;&quot;)
      if err != nil {
          log.Fatal(&quot;Listen:&quot;, err)
      }
  
      n, err := conn.WriteTo([]byte(&quot;hello&quot;), &amp;addr)
      if err != nil {
          log.Fatal(&quot;Error while writing to conn! :&quot;, err)
      }
  
      conn.Close()
  }
  </code></pre>
  <p>THREADS is defined by runtime.NumCPU() btw.
  Benchmarking this using Wireshark gives these results:
  <a href="https://i.stack.imgur.com/UCpdX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UCpdX.jpg" alt="Golang benchmark" /></a>
  About 90ms delay (if I'm reading this right).</p>
  <p>While this is the situation in Python (this function is running in 4 threads):</p>
  <pre><code>def sendHello():
      while True:
          try:
              sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
              addr = (&quot;192.168.1.xxx&quot;, 1337)
              s.sendto(data, addr)
          except:
              print(&quot;error&quot;)
  </code></pre>
  <p>Benchmark using Wireshark: <a href="https://i.stack.imgur.com/dljOO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dljOO.jpg" alt="py bench" /></a>. This is from 1ms to about 10ms delay! Insane differences.</p>
  <p>How can I match python's speed in Go?</p>