profile.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package toolbox
  15. import (
  16. "fmt"
  17. "io"
  18. "log"
  19. "os"
  20. "path"
  21. "runtime"
  22. "runtime/debug"
  23. "runtime/pprof"
  24. "strconv"
  25. "time"
  26. )
  27. var startTime = time.Now()
  28. var pid int
  29. func init() {
  30. pid = os.Getpid()
  31. }
  32. // ProcessInput parse input command string
  33. func ProcessInput(input string, w io.Writer) {
  34. switch input {
  35. case "lookup goroutine":
  36. p := pprof.Lookup("goroutine")
  37. p.WriteTo(w, 2)
  38. case "lookup heap":
  39. p := pprof.Lookup("heap")
  40. p.WriteTo(w, 2)
  41. case "lookup threadcreate":
  42. p := pprof.Lookup("threadcreate")
  43. p.WriteTo(w, 2)
  44. case "lookup block":
  45. p := pprof.Lookup("block")
  46. p.WriteTo(w, 2)
  47. case "get cpuprof":
  48. GetCPUProfile(w)
  49. case "get memprof":
  50. MemProf(w)
  51. case "gc summary":
  52. PrintGCSummary(w)
  53. }
  54. }
  55. // MemProf record memory profile in pprof
  56. func MemProf(w io.Writer) {
  57. filename := "mem-" + strconv.Itoa(pid) + ".memprof"
  58. if f, err := os.Create(filename); err != nil {
  59. fmt.Fprintf(w, "create file %s error %s\n", filename, err.Error())
  60. log.Fatal("record heap profile failed: ", err)
  61. } else {
  62. runtime.GC()
  63. pprof.WriteHeapProfile(f)
  64. f.Close()
  65. fmt.Fprintf(w, "create heap profile %s \n", filename)
  66. _, fl := path.Split(os.Args[0])
  67. fmt.Fprintf(w, "Now you can use this to check it: go tool pprof %s %s\n", fl, filename)
  68. }
  69. }
  70. // GetCPUProfile start cpu profile monitor
  71. func GetCPUProfile(w io.Writer) {
  72. sec := 30
  73. filename := "cpu-" + strconv.Itoa(pid) + ".pprof"
  74. f, err := os.Create(filename)
  75. if err != nil {
  76. fmt.Fprintf(w, "Could not enable CPU profiling: %s\n", err)
  77. log.Fatal("record cpu profile failed: ", err)
  78. }
  79. pprof.StartCPUProfile(f)
  80. time.Sleep(time.Duration(sec) * time.Second)
  81. pprof.StopCPUProfile()
  82. fmt.Fprintf(w, "create cpu profile %s \n", filename)
  83. _, fl := path.Split(os.Args[0])
  84. fmt.Fprintf(w, "Now you can use this to check it: go tool pprof %s %s\n", fl, filename)
  85. }
  86. // PrintGCSummary print gc information to io.Writer
  87. func PrintGCSummary(w io.Writer) {
  88. memStats := &runtime.MemStats{}
  89. runtime.ReadMemStats(memStats)
  90. gcstats := &debug.GCStats{PauseQuantiles: make([]time.Duration, 100)}
  91. debug.ReadGCStats(gcstats)
  92. printGC(memStats, gcstats, w)
  93. }
  94. func printGC(memStats *runtime.MemStats, gcstats *debug.GCStats, w io.Writer) {
  95. if gcstats.NumGC > 0 {
  96. lastPause := gcstats.Pause[0]
  97. elapsed := time.Now().Sub(startTime)
  98. overhead := float64(gcstats.PauseTotal) / float64(elapsed) * 100
  99. allocatedRate := float64(memStats.TotalAlloc) / elapsed.Seconds()
  100. fmt.Fprintf(w, "NumGC:%d Pause:%s Pause(Avg):%s Overhead:%3.2f%% Alloc:%s Sys:%s Alloc(Rate):%s/s Histogram:%s %s %s \n",
  101. gcstats.NumGC,
  102. toS(lastPause),
  103. toS(avg(gcstats.Pause)),
  104. overhead,
  105. toH(memStats.Alloc),
  106. toH(memStats.Sys),
  107. toH(uint64(allocatedRate)),
  108. toS(gcstats.PauseQuantiles[94]),
  109. toS(gcstats.PauseQuantiles[98]),
  110. toS(gcstats.PauseQuantiles[99]))
  111. } else {
  112. // while GC has disabled
  113. elapsed := time.Now().Sub(startTime)
  114. allocatedRate := float64(memStats.TotalAlloc) / elapsed.Seconds()
  115. fmt.Fprintf(w, "Alloc:%s Sys:%s Alloc(Rate):%s/s\n",
  116. toH(memStats.Alloc),
  117. toH(memStats.Sys),
  118. toH(uint64(allocatedRate)))
  119. }
  120. }
  121. func avg(items []time.Duration) time.Duration {
  122. var sum time.Duration
  123. for _, item := range items {
  124. sum += item
  125. }
  126. return time.Duration(int64(sum) / int64(len(items)))
  127. }
  128. // format bytes number friendly
  129. func toH(bytes uint64) string {
  130. switch {
  131. case bytes < 1024:
  132. return fmt.Sprintf("%dB", bytes)
  133. case bytes < 1024*1024:
  134. return fmt.Sprintf("%.2fK", float64(bytes)/1024)
  135. case bytes < 1024*1024*1024:
  136. return fmt.Sprintf("%.2fM", float64(bytes)/1024/1024)
  137. default:
  138. return fmt.Sprintf("%.2fG", float64(bytes)/1024/1024/1024)
  139. }
  140. }
  141. // short string format
  142. func toS(d time.Duration) string {
  143. u := uint64(d)
  144. if u < uint64(time.Second) {
  145. switch {
  146. case u == 0:
  147. return "0"
  148. case u < uint64(time.Microsecond):
  149. return fmt.Sprintf("%.2fns", float64(u))
  150. case u < uint64(time.Millisecond):
  151. return fmt.Sprintf("%.2fus", float64(u)/1000)
  152. default:
  153. return fmt.Sprintf("%.2fms", float64(u)/1000/1000)
  154. }
  155. } else {
  156. switch {
  157. case u < uint64(time.Minute):
  158. return fmt.Sprintf("%.2fs", float64(u)/1000/1000/1000)
  159. case u < uint64(time.Hour):
  160. return fmt.Sprintf("%.2fm", float64(u)/1000/1000/1000/60)
  161. default:
  162. return fmt.Sprintf("%.2fh", float64(u)/1000/1000/1000/60/60)
  163. }
  164. }
  165. }