Skip to content

Instantly share code, notes, and snippets.

@howardjohn
Last active May 3, 2024 19:16
Show Gist options
  • Save howardjohn/3027f9c21f71ccf8199bc4192af359ae to your computer and use it in GitHub Desktop.
Save howardjohn/3027f9c21f71ccf8199bc4192af359ae to your computer and use it in GitHub Desktop.
Go program that shows every N connections are dramatically slower
package main
import (
"flag"
"net"
"time"
"log"
)
var (
connections = flag.Int("c", 100, "connections to send")
)
func main() {
flag.Parse()
listener := spawnListener()
if err := sendTraffic(listener.Addr().String()); err != nil {
log.Fatal(err)
}
}
func spawnListener() net.Listener {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
log.Fatal(err)
}
go func() {
for {
_, err := listener.Accept()
if err != nil {
return
}
}
}()
return listener
}
func sendTraffic(addr string) error {
log.Println("starting connections", *connections)
for i := 0; i < *connections; i++ {
err := call(i, addr)
if err != nil {
return err
}
}
return nil
}
func call(c int, addr string) error {
t0 := time.Now()
_, err := net.Dial("tcp", addr)
if err != nil {
return err
}
log.Printf("connection sent n=%v latency=%v", c, time.Since(t0))
return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment