From 7c167da0efdd8e7ac8a9c6e298c6fb8d9e5f6def Mon Sep 17 00:00:00 2001 From: Nathan Baulch Date: Mon, 25 Jul 2022 11:59:06 +1000 Subject: [PATCH] Use the existing humanize function to support GB/s rates --- progressbar.go | 14 +++++--------- progressbar_test.go | 12 +++++++++++- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/progressbar.go b/progressbar.go index b67bb5b..14e2654 100644 --- a/progressbar.go +++ b/progressbar.go @@ -702,19 +702,15 @@ func renderProgressBar(c config, s *state) (int, error) { } } - // show rolling average rate in kB/sec or MB/sec - if c.showBytes { + // show rolling average rate + if c.showBytes && averageRate > 0 && !math.IsInf(averageRate, 1) { if bytesString == "" { bytesString += "(" } else { bytesString += ", " } - kbPerSecond := averageRate / 1024.0 - if kbPerSecond > 1024.0 { - bytesString += fmt.Sprintf("%0.3f MB/s", kbPerSecond/1024.0) - } else if kbPerSecond > 0 { - bytesString += fmt.Sprintf("%0.3f kB/s", kbPerSecond) - } + currentHumanize, currentSuffix := humanizeBytes(averageRate) + bytesString += fmt.Sprintf("%s%s/s", currentHumanize, currentSuffix) } // show iterations rate @@ -928,7 +924,7 @@ func humanizeBytes(s float64) (string, string) { sizes := []string{" B", " kB", " MB", " GB", " TB", " PB", " EB"} base := 1024.0 if s < 10 { - return fmt.Sprintf("%2.0f", s), "B" + return fmt.Sprintf("%2.0f", s), sizes[0] } e := math.Floor(logn(float64(s), base)) suffix := sizes[int(e)] diff --git a/progressbar_test.go b/progressbar_test.go index af5b315..3b2005b 100644 --- a/progressbar_test.go +++ b/progressbar_test.go @@ -233,7 +233,7 @@ func ExampleIgnoreLength_WithSpeed() { bar.Add(11) // Output: - // - (0.011 kB/s) + // - (11 B/s) } func TestBarSlowAdd(t *testing.T) { @@ -274,6 +274,16 @@ func TestBarSmallBytes(t *testing.T) { } } +func TestBarFastBytes(t *testing.T) { + buf := strings.Builder{} + bar := NewOptions64(1e8, OptionShowBytes(true), OptionShowCount(), OptionSetWidth(10), OptionSetWriter(&buf)) + time.Sleep(time.Millisecond) + bar.Add(1e7) + if !strings.Contains(buf.String(), " GB/s)") { + t.Errorf("wrong string: %s", buf.String()) + } +} + func TestBar(t *testing.T) { bar := New(0) if err := bar.Add(1); err == nil {