packagemainimport("io/ioutil""math/rand""net/http""os""runtime/trace""strconv""sync""time")varwgsync.WaitGroupvarhttpClient=&http.Client{Timeout:30*time.Second}funcSleepSomeTime()time.Duration{returntime.Microsecond*time.Duration(rand.Int()%1000)}funccreate(readChanchanint){deferwg.Done()fori:=0;i<500;i++{readChan<-getBodySize()SleepSomeTime()}close(readChan)}funcconvert(readChanchanint,outputchanstring){deferwg.Done()forreadChan:=rangereadChan{output<-strconv.Itoa(readChan)SleepSomeTime()}close(output)}funcoutputStr(outputchanstring){deferwg.Done()for_=rangeoutput{// do nothingSleepSomeTime()}}// 获取taobao 页面大小funcgetBodySize()int{resp,_:=httpClient.Get("https://taobao.com")res,_:=ioutil.ReadAll(resp.Body)_=resp.Body.Close()returnlen(res)}funcrun(){readChan,output:=make(chanint),make(chanstring)wg.Add(3)gocreate(readChan)goconvert(readChan,output)gooutputStr(output)}funcmain(){f,_:=os.Create("trace.out")deferf.Close()_=trace.Start(f)defertrace.Stop()run()wg.Wait()}
编译,并执行,然后启动trace;
1
2
3
4
5
6
[lipengfei5@localhost ~/blog]$ go build trace_example.go
[lipengfei5@localhost ~/blog]$ ./trace_example
[lipengfei5@localhost ~/blog]$ go tool trace -http=":8000" trace_example trace.out
2020/04/15 17:34:48 Parsing trace...
2020/04/15 17:34:50 Splitting trace...
2020/04/15 17:34:51 Opening browser. Trace viewer is listening on http://0.0.0.0:8000
然后打开浏览器,访问8000 端口即可。
Trace 功能
其中:
View trace:查看跟踪 (按照时间分段,上面我的例子时间比较短,所以没有分段)
Goroutine analysis:Goroutine 分析
Network blocking profile:网络阻塞概况
Synchronization blocking profile:同步阻塞概况
Syscall blocking profile:系统调用阻塞概况
Scheduler latency profile:调度延迟概况
User defined tasks:用户自定义任务
User defined regions:用户自定义区域
Minimum mutator utilization:最低 Mutator 利用率 (主要是GC 的评价标准, 暂时没搞懂)
//filepath: src/runtime/trace/trace.goctx,task:=trace.NewTask(ctx,"makeCappuccino")trace.Log(ctx,"orderID",orderID)milk:=make(chanbool)espresso:=make(chanbool)gofunc(){trace.WithRegion(ctx,"steamMilk",steamMilk)milk<-true}()gofunc(){trace.WithRegion(ctx,"extractCoffee",extractCoffee)espresso<-true}()gofunc(){defertask.End()// When assemble is done, the order is complete.<-espresso<-milktrace.WithRegion(ctx,"mixMilkCoffee",mixMilkCoffee)}()