Skip to content

Commit

Permalink
Add profiling support
Browse files Browse the repository at this point in the history
  • Loading branch information
bhperry committed Aug 18, 2024
1 parent 38c4522 commit cbecb73
Showing 1 changed file with 35 additions and 1 deletion.
36 changes: 35 additions & 1 deletion tools/cmd/bench.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"encoding/json"
"fmt"
"os"
"runtime"
"runtime/pprof"
"text/tabwriter"
"time"

Expand All @@ -12,7 +14,9 @@ import (
)

var (
benchRunOutput string
benchRunOutput,
benchRunCpuprofile,
benchRunMemprofile string
benchRunDuration time.Duration

benchStatsInput string
Expand All @@ -37,6 +41,20 @@ func NewBenchRunCmd() *cobra.Command {
Args: cobra.MinimumNArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
// Start CPU profile
if benchRunCpuprofile != "" {
f, err := os.Create(benchRunCpuprofile)
if err != nil {
return fmt.Errorf("could not create CPU profile: %v", err)
}
defer f.Close()
if err := pprof.StartCPUProfile(f); err != nil {
return fmt.Errorf("could not start CPU profile: %v", err)
}
defer pprof.StopCPUProfile()
}

// Run benchmark(s)
benchStats := make(benchmark.StatsCollection, len(args))
for i, name := range args {
config, err := benchmark.Benchmarks.Get(name)
Expand All @@ -55,6 +73,20 @@ func NewBenchRunCmd() *cobra.Command {
benchStats[i] = stats
}

// Dump memory profile
if benchRunMemprofile != "" {
f, err := os.Create(benchRunMemprofile)
if err != nil {
return fmt.Errorf("could not create memory profile: %v", err)
}
defer f.Close()
runtime.GC() // get up-to-date statistics
if err := pprof.WriteHeapProfile(f); err != nil {
return fmt.Errorf("could not write memory profile: %v", err)
}
}

// Dump stats
if benchRunOutput != "" {
err := benchStats.Dump(benchRunOutput)
if err != nil {
Expand All @@ -67,6 +99,8 @@ func NewBenchRunCmd() *cobra.Command {

run.Flags().StringVarP(&benchRunOutput, "output", "o", "", "Output path for statistics file")
run.Flags().DurationVarP(&benchRunDuration, "duration", "d", 0, "Override duration for benchmark runs")
run.Flags().StringVarP(&benchRunCpuprofile, "cpuprofile", "c", "", "CPU profiling file")
run.Flags().StringVarP(&benchRunMemprofile, "memprofile", "m", "", "Memory profiling file")
return run
}

Expand Down

0 comments on commit cbecb73

Please sign in to comment.