Skip to content

Instantly share code, notes, and snippets.

@adriansr
Last active January 4, 2022 15:19
Show Gist options
  • Save adriansr/9f907c5b2da0472726756a8805f8ef1c to your computer and use it in GitHub Desktop.
Save adriansr/9f907c5b2da0472726756a8805f8ef1c to your computer and use it in GitHub Desktop.
Call a syscall in a loop, optionally limiting the number of calls per second
package main
import (
"sync/atomic"
"fmt"
"os"
"strconv"
"syscall"
"time"
)
// Usage: helper <rate>
// helper 5000 for 5000 calls per second
func main() {
rate := 0
if len(os.Args) > 1 {
var err error
rate, err = strconv.Atoi(os.Args[1])
if err != nil || rate <= 0 {
fmt.Fprintln(os.Stderr, "Bad rate:", rate, err)
os.Exit(1)
}
fmt.Fprintf(os.Stderr, "Starting syscall loop [rate=%d/s]\n", rate)
} else {
fmt.Fprintln(os.Stderr, "Starting syscall loop")
}
var counter, prev uint64
var prevTime time.Time
go func() {
delay := time.Second
if rate > 0 {
delay = time.Second / time.Duration(rate)
}
next := time.Now().Add(delay)
for {
if rate > 0 {
if time.Now().Before(next) {
time.Sleep(time.Until(next))
}
next = next.Add(delay)
}
syscall.Accept(-1)
atomic.AddUint64(&counter, 1)
}
}()
tick := time.NewTicker(time.Second / 2)
for _ = range tick.C {
count := atomic.LoadUint64(&counter)
now := time.Now()
delta := count - prev
if prev != 0 {
secs := float64(now.Sub(prevTime)) / float64(time.Second)
fmt.Fprintf(os.Stderr, "\rCalled %d times [%f c/s] ", count, float64(delta) / secs)
}
prev = count
prevTime = now
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment