Skip to content

Commit

Permalink
Extra precision in the benchmark output, implementing suggestion gola…
Browse files Browse the repository at this point in the history
  • Loading branch information
voronaam authored and Lex Vorona committed Dec 11, 2019
1 parent 9d78e75 commit f1ebc33
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
13 changes: 9 additions & 4 deletions src/testing/benchmark.go
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ func (b *B) launch() {
b.runN(int(n))
}
}
b.result = BenchmarkResult{b.N, b.duration, b.bytes, b.netAllocs, b.netBytes, b.extra}
b.result = BenchmarkResult{b.N, b.duration, b.bytes, b.netAllocs, b.netBytes, b.chatty, b.extra}
}

// ReportMetric adds "n unit" to the reported benchmark results.
Expand Down Expand Up @@ -349,6 +349,7 @@ type BenchmarkResult struct {
Bytes int64 // Bytes processed in one iteration.
MemAllocs uint64 // The total number of memory allocations.
MemBytes uint64 // The total number of bytes allocated.
Chatty bool // Copy of the benchmark's chatty flag

// Extra records additional metrics reported by ReportMetric.
Extra map[string]float64
Expand Down Expand Up @@ -418,7 +419,7 @@ func (r BenchmarkResult) String() string {
}
if ns != 0 {
buf.WriteByte('\t')
prettyPrint(buf, ns, "ns/op")
prettyPrint(buf, ns, "ns/op", !r.Chatty)
}

if mbs := r.mbPerSec(); mbs != 0 {
Expand All @@ -439,12 +440,16 @@ func (r BenchmarkResult) String() string {
sort.Strings(extraKeys)
for _, k := range extraKeys {
buf.WriteByte('\t')
prettyPrint(buf, r.Extra[k], k)
prettyPrint(buf, r.Extra[k], k, !r.Chatty)
}
return buf.String()
}

func prettyPrint(w io.Writer, x float64, unit string) {
func prettyPrint(w io.Writer, x float64, unit string, humanize bool) {
if !humanize {
fmt.Fprintf(w, "%17.6f %s", x, unit)
return
}
// Print all numbers with 10 places before the decimal point
// and small numbers with three sig figs.
var format string
Expand Down
8 changes: 7 additions & 1 deletion src/testing/benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ var prettyPrintTests = []struct {
func TestPrettyPrint(t *testing.T) {
for _, tt := range prettyPrintTests {
buf := new(strings.Builder)
testing.PrettyPrint(buf, tt.v, "x")
testing.PrettyPrint(buf, tt.v, "x", true)
if tt.expected != buf.String() {
t.Errorf("prettyPrint(%v): expected %q, actual %q", tt.v, tt.expected, buf.String())
}
Expand All @@ -60,6 +60,12 @@ func TestResultString(t *testing.T) {
t.Errorf("String: expected %q, actual %q", want, got)
}

// Test extra precision output
r.Chatty = true
if want, got := " 100\t 0.400000 ns/op", r.String(); want != got {
t.Errorf("String: expected %q, actual %q", want, got)
}

// Test 0 ns/op
r.T = 0
if want, got := " 100", r.String(); want != got {
Expand Down

0 comments on commit f1ebc33

Please sign in to comment.