From a03223b86f7ade425ba6888080b355ac6d6507a5 Mon Sep 17 00:00:00 2001 From: Eloi Torrents Date: Thu, 4 Dec 2025 22:22:41 +0100 Subject: [PATCH] cmd/bench: support writing benchmark output to file (#13263) * cmd/bench: support writing benchmark output to file This changes Ollama to allow the bench command to write benchmark results to a user-specified output file instead of stdout when the --output flag is provided. --------- Co-authored-by: Patrick Devine --- cmd/bench/bench.go | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/cmd/bench/bench.go b/cmd/bench/bench.go index 25df1817a..53721f877 100644 --- a/cmd/bench/bench.go +++ b/cmd/bench/bench.go @@ -48,8 +48,8 @@ func OutputMetrics(w io.Writer, format string, metrics []Metrics, verbose bool) case "benchstat": if verbose { printHeader := func() { - fmt.Printf("sysname: %s\n", runtime.GOOS) - fmt.Printf("machine: %s\n", runtime.GOARCH) + fmt.Fprintf(w, "sysname: %s\n", runtime.GOOS) + fmt.Fprintf(w, "machine: %s\n", runtime.GOARCH) } once.Do(printHeader) } @@ -147,6 +147,17 @@ func BenchmarkChat(fOpt flagOptions) error { return err } + var out io.Writer = os.Stdout + if fOpt.outputFile != nil && *fOpt.outputFile != "" { + f, err := os.OpenFile(*fOpt.outputFile, os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + fmt.Fprintf(os.Stderr, "ERROR: cannot open output file %s: %v\n", *fOpt.outputFile, err) + return err + } + defer f.Close() + out = f + } + for _, model := range models { for range *fOpt.epochs { options := make(map[string]interface{}) @@ -241,13 +252,14 @@ func BenchmarkChat(fOpt flagOptions) error { }, } - OutputMetrics(os.Stdout, *fOpt.format, metrics, *fOpt.verbose) + OutputMetrics(out, *fOpt.format, metrics, *fOpt.verbose) if *fOpt.keepAlive > 0 { time.Sleep(time.Duration(*fOpt.keepAlive*float64(time.Second)) + 200*time.Millisecond) } } } + return nil }