go-zero/core/prof/profiler.go

64 lines
1.2 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package prof
import "github.com/zeromicro/go-zero/core/utils"
2020-07-26 17:09:05 +08:00
type (
2021-02-22 10:20:54 +08:00
// A ProfilePoint is a profile time point.
2020-07-26 17:09:05 +08:00
ProfilePoint struct {
*utils.ElapsedTimer
}
2021-02-22 10:20:54 +08:00
// A Profiler interface represents a profiler that used to report profile points.
2020-07-26 17:09:05 +08:00
Profiler interface {
Start() ProfilePoint
Report(name string, point ProfilePoint)
}
2021-02-22 10:20:54 +08:00
realProfiler struct{}
2020-07-26 17:09:05 +08:00
2021-02-22 10:20:54 +08:00
nullProfiler struct{}
2020-07-26 17:09:05 +08:00
)
var profiler = newNullProfiler()
2021-02-22 10:20:54 +08:00
// EnableProfiling enables profiling.
2020-07-26 17:09:05 +08:00
func EnableProfiling() {
profiler = newRealProfiler()
}
2021-02-22 10:20:54 +08:00
// Start starts a Profiler, and returns a start profiling point.
2020-07-26 17:09:05 +08:00
func Start() ProfilePoint {
return profiler.Start()
}
2021-02-22 10:20:54 +08:00
// Report reports a ProfilePoint with given name.
2020-07-26 17:09:05 +08:00
func Report(name string, point ProfilePoint) {
profiler.Report(name, point)
}
func newRealProfiler() Profiler {
2021-02-22 10:20:54 +08:00
return &realProfiler{}
2020-07-26 17:09:05 +08:00
}
2021-02-22 10:20:54 +08:00
func (rp *realProfiler) Start() ProfilePoint {
2020-07-26 17:09:05 +08:00
return ProfilePoint{
ElapsedTimer: utils.NewElapsedTimer(),
}
}
2021-02-22 10:20:54 +08:00
func (rp *realProfiler) Report(name string, point ProfilePoint) {
2020-07-26 17:09:05 +08:00
duration := point.Duration()
report(name, duration)
}
func newNullProfiler() Profiler {
2021-02-22 10:20:54 +08:00
return &nullProfiler{}
2020-07-26 17:09:05 +08:00
}
2021-02-22 10:20:54 +08:00
func (np *nullProfiler) Start() ProfilePoint {
2020-07-26 17:09:05 +08:00
return ProfilePoint{}
}
2021-02-22 10:20:54 +08:00
func (np *nullProfiler) Report(string, ProfilePoint) {
2020-07-26 17:09:05 +08:00
}