diff --git a/metrics/metrics.go b/metrics/metrics.go index 08d9322ab..aca7c4c9b 100644 --- a/metrics/metrics.go +++ b/metrics/metrics.go @@ -178,15 +178,29 @@ func (s *Store) WriteMetrics(w io.Writer) { } sort.Sort(bySum(results)) + for _, v := range results { if s.calculateHints { - fmt.Fprintf(w, " %15s %12s %12s %9d %7.f %6d %5d %s\n", v.sum, v.avg, v.max, v.cacheFactor, float64(v.cacheCount)/float64(v.count)*100, v.cacheCount, v.count, v.key) + fmt.Fprintf(w, " %15s %12s %12s %9d %7.f %6d %5d %s\n", formatDuration(v.sum), formatDuration(v.avg), formatDuration(v.max), v.cacheFactor, float64(v.cacheCount)/float64(v.count)*100, v.cacheCount, v.count, v.key) } else { - fmt.Fprintf(w, " %15s %12s %12s %5d %s\n", v.sum, v.avg, v.max, v.count, v.key) + fmt.Fprintf(w, " %15s %12s %12s %5d %s\n", formatDuration(v.sum), formatDuration(v.avg), formatDuration(v.max), v.count, v.key) } } } +func formatDuration(d time.Duration) string { + switch { + case d >= time.Second: + return fmt.Sprintf("%.2f s", float64(d)/float64(time.Second)) // additional spacing between value and unit + case d >= time.Millisecond: + return fmt.Sprintf("%.2f ms", float64(d)/float64(time.Millisecond)) + case d >= time.Microsecond: + return fmt.Sprintf("%.2f µs", float64(d)/float64(time.Microsecond)) + default: + return fmt.Sprintf("%.2f ns", float64(d)/float64(time.Nanosecond)) + } +} + // A result represents the calculated results for a given metric. type result struct { key string diff --git a/metrics/metrics_test.go b/metrics/metrics_test.go index 83dc1433f..1e5221ec1 100644 --- a/metrics/metrics_test.go +++ b/metrics/metrics_test.go @@ -17,6 +17,7 @@ import ( "html/template" "strings" "testing" + "time" "github.com/gohugoio/hugo/resources/page" @@ -66,3 +67,21 @@ func BenchmarkHowSimilar(b *testing.B) { howSimilar(s1, s2) } } + +func TestFormatDuration(t *testing.T) { + c := qt.New(t) + tests := []struct { + duration time.Duration + want string + }{ + {4*time.Second + 342*time.Millisecond, "4.34 s"}, // additional spacing between value and unit + {170*time.Millisecond + 289*time.Microsecond, "170.29 ms"}, + {16*time.Microsecond + 90*time.Nanosecond, "16.09 µs"}, + {147 * time.Nanosecond, "147.00 ns"}, + } + + for _, tt := range tests { + got := formatDuration(tt.duration) + c.Assert(got, qt.Equals, tt.want) + } +} diff --git a/tpl/partials/partials_integration_test.go b/tpl/partials/partials_integration_test.go index dc49cbdc5..58b4248c0 100644 --- a/tpl/partials/partials_integration_test.go +++ b/tpl/partials/partials_integration_test.go @@ -170,8 +170,8 @@ D1 got := buf.String() - // Get rid of all the durations, they are never the same. - durationRe := regexp.MustCompile(`\b[\.\d]*(ms|ns|µs|s)\b`) + // Get rid of all the durations, including the space and unit, they are never the same. + durationRe := regexp.MustCompile(`\b[\.\d]*\s*(ms|ns|µs|s)\b`) normalize := func(s string) string { s = durationRe.ReplaceAllString(s, "")