From ce2c9ff07ea024b5c883139dd916cd31ca600a08 Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Wed, 18 Apr 2018 11:54:25 -0400 Subject: track+print how long each job takes --- jwg.go | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/jwg.go b/jwg.go index 8daf046..2bde209 100644 --- a/jwg.go +++ b/jwg.go @@ -11,7 +11,7 @@ import ( type JobWaitGroup struct { lock sync.RWMutex - jobs map[string]bool + jobs map[string]time.Duration wg sync.WaitGroup } @@ -20,18 +20,19 @@ func (jwg *JobWaitGroup) Do(name string, fn func()) { defer jwg.lock.Unlock() if jwg.jobs == nil { - jwg.jobs = make(map[string]bool) + jwg.jobs = make(map[string]time.Duration) } if _, dup := jwg.jobs[name]; dup { panic(fmt.Sprintf("job %q already exists", name)) } - jwg.jobs[name] = true + jwg.jobs[name] = -1 jwg.wg.Add(1) + start := time.Now() go func() { defer func() { jwg.lock.Lock() defer jwg.lock.Unlock() - jwg.jobs[name] = false + jwg.jobs[name] = time.Now().Sub(start) jwg.wg.Done() }() fn() @@ -47,8 +48,8 @@ func (jwg *JobWaitGroup) Status() (int, []string) { n := len(jwg.jobs) var jobs []string - for job, active := range jwg.jobs { - if active { + for job, duration := range jwg.jobs { + if duration < 0 { jobs = append(jobs, job) } } @@ -80,7 +81,31 @@ func (jwg *JobWaitGroup) Watch(d time.Duration) { fmt.Fprintf(os.Stderr, "\r%-70s", line) case <-done: fmt.Fprintf(os.Stderr, "\r%-70s\n", "done") + jwg.lock.RLock() + defer jwg.lock.RUnlock() + s := newSortHelper(jwg.jobs) + sort.Sort(s) + for _, job := range s.StringSlice { + fmt.Fprintln(os.Stderr, s.times[job], job) + } return } } } + +type sortHelper struct { + times map[string]time.Duration + sort.StringSlice +} + +func (s sortHelper) Less(i, j int) bool { + return s.times[s.StringSlice[i]] < s.times[s.StringSlice[j]] +} + +func newSortHelper(jobs map[string]time.Duration) sortHelper { + slice := make([]string, 0, len(jobs)) + for job := range jobs { + slice = append(slice, job) + } + return sortHelper{times: jobs, StringSlice: slice} +} -- cgit v1.2.3