metrics: Improve template metrics duration formatting

Fixes #15027
This commit is contained in:
Shiwang Bisht
2026-08-24 15:06:58 +05:30
committed by GitHub
parent 723579ff54
commit a25af7facf
3 changed files with 37 additions and 4 deletions
+16 -2
View File
@@ -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
+19
View File
@@ -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)
}
}
+2 -2
View File
@@ -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, "")