Skip to content

Instantly share code, notes, and snippets.

@erikdubbelboer
Created September 25, 2019 11:19
Show Gist options
  • Save erikdubbelboer/7b8f2f5af796ebacb087fb866e9b8dc2 to your computer and use it in GitHub Desktop.
Save erikdubbelboer/7b8f2f5af796ebacb087fb866e9b8dc2 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net"
"sync/atomic"
"time"
)
func main() {
ln, err := net.Listen("tcp", ":8080")
if err != nil {
panic(err)
}
go func() {
for {
conn, err := ln.Accept()
if err != nil {
panic(err)
}
go func() {
for {
buff := make([]byte, 4)
if _, err := conn.Read(buff); err != nil {
panic(err)
}
time.Sleep(time.Millisecond * 200)
if _, err := conn.Write(buff); err != nil {
panic(err)
}
}
}()
}
}()
duration := int64(0)
count := int64(0)
connections := int64(0)
go func() {
for {
for i := 0; i < 400; i++ {
go func() {
conn, err := net.Dial("tcp", "localhost:8080")
if err != nil {
panic(err)
}
atomic.AddInt64(&connections, 1)
for {
start := time.Now()
buff := []byte{1, 2, 3, 4}
if _, err := conn.Write(buff); err != nil {
panic(err)
}
if _, err := conn.Read(buff); err != nil {
panic(err)
}
atomic.AddInt64(&duration, int64(time.Since(start)))
atomic.AddInt64(&count, 1)
}
}()
time.Sleep(time.Millisecond)
}
time.Sleep(time.Second * 4)
}
}()
for {
time.Sleep(time.Second)
d := atomic.SwapInt64(&duration, 0)
c := atomic.SwapInt64(&count, 0)
n := atomic.LoadInt64(&connections)
if c > 0 {
fmt.Printf("% 4d: %v (%d)\n", n, time.Duration(d/c), c)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment