Skip to content

Commit

Permalink
Merge pull request #125 from NathanBaulch/humanize-byte-rate
Browse files Browse the repository at this point in the history
Use the existing humanize function to support GB/s rates
  • Loading branch information
schollz committed Jul 31, 2022
2 parents 0d4fc1b + 7c167da commit 3ebeac9
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
14 changes: 5 additions & 9 deletions progressbar.go
Expand Up @@ -706,19 +706,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
Expand Down Expand Up @@ -935,7 +931,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)]
Expand Down
12 changes: 11 additions & 1 deletion progressbar_test.go
Expand Up @@ -232,7 +232,7 @@ func ExampleIgnoreLength_WithSpeed() {
bar.Add(11)

// Output:
// - (0.011 kB/s)
// - (11 B/s)
}

func TestBarSlowAdd(t *testing.T) {
Expand Down Expand Up @@ -273,6 +273,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 {
Expand Down

0 comments on commit 3ebeac9

Please sign in to comment.