profiler.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package prof
  2. import "github.com/tal-tech/go-zero/core/utils"
  3. type (
  4. // A ProfilePoint is a profile time point.
  5. ProfilePoint struct {
  6. *utils.ElapsedTimer
  7. }
  8. // A Profiler interface represents a profiler that used to report profile points.
  9. Profiler interface {
  10. Start() ProfilePoint
  11. Report(name string, point ProfilePoint)
  12. }
  13. realProfiler struct{}
  14. nullProfiler struct{}
  15. )
  16. var profiler = newNullProfiler()
  17. // EnableProfiling enables profiling.
  18. func EnableProfiling() {
  19. profiler = newRealProfiler()
  20. }
  21. // Start starts a Profiler, and returns a start profiling point.
  22. func Start() ProfilePoint {
  23. return profiler.Start()
  24. }
  25. // Report reports a ProfilePoint with given name.
  26. func Report(name string, point ProfilePoint) {
  27. profiler.Report(name, point)
  28. }
  29. func newRealProfiler() Profiler {
  30. return &realProfiler{}
  31. }
  32. func (rp *realProfiler) Start() ProfilePoint {
  33. return ProfilePoint{
  34. ElapsedTimer: utils.NewElapsedTimer(),
  35. }
  36. }
  37. func (rp *realProfiler) Report(name string, point ProfilePoint) {
  38. duration := point.Duration()
  39. report(name, duration)
  40. }
  41. func newNullProfiler() Profiler {
  42. return &nullProfiler{}
  43. }
  44. func (np *nullProfiler) Start() ProfilePoint {
  45. return ProfilePoint{}
  46. }
  47. func (np *nullProfiler) Report(string, ProfilePoint) {
  48. }