sigar_format.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. // Copyright (c) 2012 VMware, Inc.
  2. package sigar
  3. import (
  4. "bufio"
  5. "bytes"
  6. "fmt"
  7. "strconv"
  8. "time"
  9. )
  10. // Go version of apr_strfsize
  11. func FormatSize(size uint64) string {
  12. ord := []string{"K", "M", "G", "T", "P", "E"}
  13. o := 0
  14. buf := new(bytes.Buffer)
  15. w := bufio.NewWriter(buf)
  16. if size < 973 {
  17. fmt.Fprintf(w, "%3d ", size)
  18. w.Flush()
  19. return buf.String()
  20. }
  21. for {
  22. remain := size & 1023
  23. size >>= 10
  24. if size >= 973 {
  25. o++
  26. continue
  27. }
  28. if size < 9 || (size == 9 && remain < 973) {
  29. remain = ((remain * 5) + 256) / 512
  30. if remain >= 10 {
  31. size++
  32. remain = 0
  33. }
  34. fmt.Fprintf(w, "%d.%d%s", size, remain, ord[o])
  35. break
  36. }
  37. if remain >= 512 {
  38. size++
  39. }
  40. fmt.Fprintf(w, "%3d%s", size, ord[o])
  41. break
  42. }
  43. w.Flush()
  44. return buf.String()
  45. }
  46. func FormatPercent(percent float64) string {
  47. return strconv.FormatFloat(percent, 'f', -1, 64) + "%"
  48. }
  49. func (self *FileSystemUsage) UsePercent() float64 {
  50. b_used := (self.Total - self.Free) / 1024
  51. b_avail := self.Avail / 1024
  52. utotal := b_used + b_avail
  53. used := b_used
  54. if utotal != 0 {
  55. u100 := used * 100
  56. pct := u100 / utotal
  57. if u100%utotal != 0 {
  58. pct += 1
  59. }
  60. return (float64(pct) / float64(100)) * 100.0
  61. }
  62. return 0.0
  63. }
  64. func (self *Uptime) Format() string {
  65. buf := new(bytes.Buffer)
  66. w := bufio.NewWriter(buf)
  67. uptime := uint64(self.Length)
  68. days := uptime / (60 * 60 * 24)
  69. if days != 0 {
  70. s := ""
  71. if days > 1 {
  72. s = "s"
  73. }
  74. fmt.Fprintf(w, "%d day%s, ", days, s)
  75. }
  76. minutes := uptime / 60
  77. hours := minutes / 60
  78. hours %= 24
  79. minutes %= 60
  80. fmt.Fprintf(w, "%2d:%02d", hours, minutes)
  81. w.Flush()
  82. return buf.String()
  83. }
  84. func (self *ProcTime) FormatStartTime() string {
  85. if self.StartTime == 0 {
  86. return "00:00"
  87. }
  88. start := time.Unix(int64(self.StartTime)/1000, 0)
  89. format := "Jan02"
  90. if time.Since(start).Seconds() < (60 * 60 * 24) {
  91. format = "15:04"
  92. }
  93. return start.Format(format)
  94. }
  95. func (self *ProcTime) FormatTotal() string {
  96. t := self.Total / 1000
  97. ss := t % 60
  98. t /= 60
  99. mm := t % 60
  100. t /= 60
  101. hh := t % 24
  102. return fmt.Sprintf("%02d:%02d:%02d", hh, mm, ss)
  103. }