format.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package shared
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func FormatCount(n int64) string {
  7. switch {
  8. case n >= 1_000_000_000:
  9. return fmt.Sprintf("%.1fB", float64(n)/1_000_000_000)
  10. case n >= 1_000_000:
  11. return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
  12. case n >= 1_000:
  13. return fmt.Sprintf("%.1fk", float64(n)/1_000)
  14. default:
  15. return fmt.Sprintf("%d", n)
  16. }
  17. }
  18. func FormatBytes(b int64) string {
  19. switch {
  20. case b >= 1<<30:
  21. return fmt.Sprintf("%.1fGB", float64(b)/(1<<30))
  22. case b >= 1<<20:
  23. return fmt.Sprintf("%.1fMB", float64(b)/(1<<20))
  24. case b >= 1<<10:
  25. return fmt.Sprintf("%.1fKB", float64(b)/(1<<10))
  26. default:
  27. return fmt.Sprintf("%dB", b)
  28. }
  29. }
  30. // Rate computes per-second rate from two counter snapshots.
  31. func Rate(prev, curr int64, dt time.Duration) float64 {
  32. sec := dt.Seconds()
  33. if sec <= 0 {
  34. return 0
  35. }
  36. return float64(curr-prev) / sec
  37. }
  38. // FormatRate formats a per-second rate. For non-byte rates isBytes=false.
  39. func FormatRate(val float64, humanize, isBytes bool) string {
  40. if !humanize {
  41. return fmt.Sprintf("%.0f/s", val)
  42. }
  43. if isBytes {
  44. return FormatBytes(int64(val)) + "/s"
  45. }
  46. return FormatCount(int64(val)) + "/s"
  47. }