pprof.go 980 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package grace
  2. import (
  3. "os"
  4. "runtime"
  5. "runtime/pprof"
  6. "github.com/seaweedfs/seaweedfs/weed/glog"
  7. )
  8. func SetupProfiling(cpuProfile, memProfile string) {
  9. if cpuProfile != "" {
  10. f, err := os.Create(cpuProfile)
  11. if err != nil {
  12. glog.Fatal(err)
  13. }
  14. runtime.SetBlockProfileRate(1)
  15. runtime.SetMutexProfileFraction(1)
  16. pprof.StartCPUProfile(f)
  17. OnInterrupt(func() {
  18. pprof.StopCPUProfile()
  19. // write block pprof
  20. blockF, err := os.Create(cpuProfile + ".block")
  21. if err != nil {
  22. return
  23. }
  24. p := pprof.Lookup("block")
  25. p.WriteTo(blockF, 0)
  26. blockF.Close()
  27. // write mutex pprof
  28. mutexF, err := os.Create(cpuProfile + ".mutex")
  29. if err != nil {
  30. return
  31. }
  32. p = pprof.Lookup("mutex")
  33. p.WriteTo(mutexF, 0)
  34. mutexF.Close()
  35. })
  36. }
  37. if memProfile != "" {
  38. runtime.MemProfileRate = 1
  39. f, err := os.Create(memProfile)
  40. if err != nil {
  41. glog.Fatal(err)
  42. }
  43. OnInterrupt(func() {
  44. pprof.WriteHeapProfile(f)
  45. f.Close()
  46. })
  47. }
  48. }