github.com/lingyao2333/mo-zero@v1.4.1/core/prof/profiler.go (about)

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