5. 统计协程耗时
type MyWaitGroup struct {
sync.WaitGroup
cost int64
}
func test1() {
time.Sleep(time.Second * 3)
}
func test2() {
time.Sleep(time.Second * 1)
}
func test3() {
time.Sleep(time.Second * 2)
}
func doWork(wg *MyWaitGroup, fns ...func()) {
for _, fn := range fns {
wg.Add(1)
go func(fn func()) {
defer wg.Done()
defer func(t time.Time) {
wg.cost += time.Since(t).Milliseconds() / 1000
}(time.Now())
fn()
}(fn)
}
}
func main() {
now := time.Now()
var wg MyWaitGroup
doWork(&wg, test1, test2, test3)
wg.Wait()
fmt.Println(time.Since(now).Milliseconds() / 1000)
fmt.Println(wg.cost)
}最后更新于