bbgo_origin/pkg/profile/timeprofile/timeprofile.go

52 lines
1001 B
Go
Raw Permalink Normal View History

package timeprofile
2021-06-09 15:52:16 +00:00
2022-06-02 08:51:44 +00:00
import (
"time"
)
2021-06-09 15:52:16 +00:00
type logFunction func(format string, args ...interface{})
2021-06-09 15:52:16 +00:00
type TimeProfile struct {
2022-06-02 08:51:44 +00:00
Name string
2021-06-09 15:52:16 +00:00
StartTime, EndTime time.Time
Duration time.Duration
}
func Start(args ...string) TimeProfile {
2022-06-02 08:51:44 +00:00
name := ""
if len(args) > 0 {
name = args[0]
}
2022-06-02 08:51:44 +00:00
return TimeProfile{StartTime: time.Now(), Name: name}
2021-06-09 15:52:16 +00:00
}
// TilNow returns the duration from the start time to now
2021-06-09 15:52:16 +00:00
func (p *TimeProfile) TilNow() time.Duration {
2022-06-17 11:19:51 +00:00
return time.Since(p.StartTime)
2021-06-09 15:52:16 +00:00
}
// Stop stops the time profile, set the end time and returns the duration
2021-06-09 15:52:16 +00:00
func (p *TimeProfile) Stop() time.Duration {
p.EndTime = time.Now()
p.Duration = p.EndTime.Sub(p.StartTime)
return p.Duration
}
2022-06-02 08:51:44 +00:00
// Do runs the function f and stops the time profile
func (p *TimeProfile) Do(f func()) {
defer p.Stop()
f()
}
2022-06-02 08:51:44 +00:00
func (p *TimeProfile) StopAndLog(f logFunction) {
duration := p.Stop()
s := "[profile] "
if len(p.Name) > 0 {
s += p.Name
}
s += " " + duration.String()
f(s)
}