Skip to content

Instantly share code, notes, and snippets.

@junegunn
Created May 23, 2026 12:59
Show Gist options
  • Select an option

  • Save junegunn/4660b4aea9c158bb0f45f97b401d52d9 to your computer and use it in GitHub Desktop.

Select an option

Save junegunn/4660b4aea9c158bb0f45f97b401d52d9 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
"os/exec"
"sort"
"strings"
"time"
)
const (
iterations = 500
trials = 5
)
func bench(label string, size int, shell bool) {
var env []string
env = append(env, os.Environ()...)
if size > 0 {
env = append(env, "FZF_CURRENT_ITEM="+strings.Repeat("x", size))
}
// Warmup
for i := 0; i < 20; i++ {
c := makeCmd(shell)
c.Env = env
_ = c.Run()
}
medians := make([]float64, 0, trials)
for t := 0; t < trials; t++ {
start := time.Now()
for i := 0; i < iterations; i++ {
c := makeCmd(shell)
c.Env = env
if err := c.Run(); err != nil {
fmt.Fprintln(os.Stderr, "err:", err)
return
}
}
elapsed := time.Since(start)
perCall := float64(elapsed.Microseconds()) / float64(iterations) / 1000.0 // ms
medians = append(medians, perCall)
}
sort.Float64s(medians)
median := medians[len(medians)/2]
min := medians[0]
max := medians[len(medians)-1]
mode := "direct"
if shell {
mode = "sh -c"
}
fmt.Printf("%-10s %-8s env=%7d B per-call median=%6.3f ms min=%6.3f max=%6.3f\n",
label, mode, size, median, min, max)
}
func makeCmd(shell bool) *exec.Cmd {
if shell {
return exec.Command("sh", "-c", "true")
}
return exec.Command("/usr/bin/true")
}
func main() {
fmt.Printf("iterations per trial: %d, trials: %d\n\n", iterations, trials)
sizes := []struct {
label string
size int
}{
{"baseline", 0},
{"100B", 100},
{"1KB", 1024},
{"10KB", 10 * 1024},
{"100KB", 100 * 1024},
{"500KB", 500 * 1024},
}
fmt.Println("=== direct exec (/usr/bin/true) ===")
for _, s := range sizes {
bench(s.label, s.size, false)
}
fmt.Println("\n=== via shell (sh -c true) ===")
for _, s := range sizes {
bench(s.label, s.size, true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment