Skip to content

Instantly share code, notes, and snippets.

@weaming
Last active March 19, 2021 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weaming/12fcdbdf3d488a3e6478f46240ef813c to your computer and use it in GitHub Desktop.
Save weaming/12fcdbdf3d488a3e6478f46240ef813c to your computer and use it in GitHub Desktop.
import (
"fmt"
"log"
"os"
"sync"
"time"
)
var KEEP_CALLS = os.Getenv("KEEP_CALLS") != ""
type Period struct {
Start, End *time.Time
Period time.Duration
Done bool
}
type Calls struct {
sync.RWMutex
calls map[string]map[string]*Period
Total, Done uint64
}
var GlobalCalls = Calls{
calls: map[string]map[string]*Period{},
Total: 0, Done: 0,
}
func (r *Calls) CountDone(name string) (uint64, uint64) {
r.RLock()
defer r.RUnlock()
return r.Done, r.Total
}
func (r *Calls) Start(name string) func() {
r.Lock()
defer r.Unlock()
r.Total++
id := fmt.Sprintf("%d", r.Total)
start := time.Now()
log.Println("trace start:", id, name, start.Format(time.RFC3339))
p := &Period{
Start: &start,
End: nil,
Period: time.Duration(0),
Done: false,
}
if KEEP_CALLS {
if cs, ok := r.calls[name]; ok {
cs[id] = p
} else {
r.calls[name] = map[string]*Period{id: p}
}
}
endFunc := func() {
r.Lock()
defer r.Unlock()
r.Done++
end := time.Now()
p.End = &end
p.Done = true
p.Period = p.End.Sub(*p.Start)
log.Println("trace end:", id, name, p.Start.Format(time.RFC3339), p.End.Format(time.RFC3339), p.Period)
}
return endFunc
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment