Skip to content

Instantly share code, notes, and snippets.

@pior
Created July 21, 2021 13:38
Show Gist options
  • Save pior/f72219a1496d44fb3a26d2ecce4fb8a0 to your computer and use it in GitHub Desktop.
Save pior/f72219a1496d44fb3a26d2ecce4fb8a0 to your computer and use it in GitHub Desktop.
Benchmark tools
package badger
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/montanaflynn/stats"
)
func DirSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
size += info.Size()
}
return err
})
return size, err
}
type timer struct {
start time.Time
lapStart time.Time
laps []time.Duration
lapCount int
}
func Timer() *timer {
t := &timer{}
t.Reset()
return t
}
func (t *timer) Reset() {
t.start = time.Now()
t.lapStart = t.start
t.laps = []time.Duration{}
}
func (t *timer) LapTime() {
t.laps = append(t.laps, time.Since(t.lapStart))
t.lapStart = time.Now()
}
func (t *timer) Lap() {
t.lapCount++
}
func (t *timer) ReportLaps() {
total := time.Since(t.lapStart)
avgTime := total / time.Duration(t.lapCount)
fmt.Printf("Laps=%d avgLapTime=%s avgLapRate=%.1f/s\n", t.lapCount, avgTime, 1/avgTime.Seconds())
t.lapStart = time.Now()
t.lapCount = 0
}
func (t *timer) Report(title string) {
total := time.Since(t.start)
var statsStr string
if t.lapCount != 0 {
statsStr = fmt.Sprintf(" laps=%d avgLapTime=%s", t.lapCount, total/time.Duration(t.lapCount))
}
if len(t.laps) != 0 {
data := make(stats.Float64Data, len(t.laps))
for i, lap := range t.laps {
data[i] = lap.Seconds()
}
toDuration := func(value float64, _ error) time.Duration {
return time.Duration(float64(time.Second) * value)
}
statsStr = fmt.Sprintf(" min=%s median=%s p95=%s max=%s",
toDuration(stats.Min(data)),
toDuration(stats.Median(data)),
toDuration(stats.Percentile(data, 95)),
toDuration(stats.Max(data)),
)
}
fmt.Printf("Timer %s: total=%s%s\n", title, total, statsStr)
t.Reset()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment