golang 查看程序的運行時間和CPU利用率


(1.) 使用系統自帶的time工具查看

time -v  go run test.go

(2.)使用top命令

top -p $(pidof 二進制)

(3.)GODEBUG和gctrace

執行程序之前,添加環境變量GODEBUG='gctrace=1'來跟蹤垃圾回收信息。

GODEBUG='gctrace=1' ./xxx

(4.) 利用runtime.ReadMemStats()方法

func readMemStats(){
	var ms runtime.MemStats
	runtime.ReadMemStats(&ms)
	log.Printf(Alloc:%d(bytes) HeadIdle:%d(bytes) HeadReleased:%d(bytes))
}
// 說明:將該方法,放到要執行函數的前后,即可查看內存情況

(5.)使用pprof工具

import(
_ "net/http/pprof"
)

func main(){
	// 啟動pprof
	go func(){
		log.Println(http.ListenAndServer("0.0.0.0:10000"),nil)
	}()
}

//(1.) 瀏覽器訪問:
http://127.0.0.1:10000/debug/pprof/heap?debug=1   // 查看內存情況

//(2.) 使用go tool pprof工具查看
go tool pprof [binary] [profile]
binary:必須指向生成這個性能分析數據的二進制文件
profile:必須是該二進制文件所生成的性能分析數據文件

示例:
go tool pprof ./demo profile
go tool pprof ./demo profileFile:demo //如果找不到grapviz需要安裝



數據說明:
flat:當前函數CPU耗時
sun%:當前函數占用CPU耗時百分比
cum:當前函數+調用當前函數占用的CPU總耗時

(3.)先啟動程序,生成proflie文件后再查看
示例:
./demo
go tool pprof http://localhost:10000/debug/pprof/profile?seconds=60


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM