這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
Go 中監控代碼效能的有兩個包:
- net/http/pprof
- runtime/pprof
這兩個包都是可以監控代碼效能的, 只不過net/http/pprof是通過http連接埠方式暴露出來的,內部封裝的仍然是runtime/pprof。
runtime/pprof 的用法樣本
這裡的例子我們用 遞迴實現的費伯納西數列來測試效能,費伯納西數列 的代碼如下:
package main
import (
"fmt"
)
func main() {
for i := 0; i < 10; i++ {
nums := fibonacci(i)
fmt.Println(nums)
}
}
func fibonacci(num int) int {
if num < 2 {
return 1
}
return fibonacci(num-1) + fibonacci(num-2)
}
我們對這裡的代碼做了部分改造,以便可以採集效能資料:
package main
import (
"flag"
"fmt"
"log"
"os"
"runtime/pprof"
)
var (
cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file.")
)
func main() {
log.Println("begin")
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
for i := 0; i < 30; i++ {
nums := fibonacci(i)
fmt.Println(nums)
}
}
func fibonacci(num int) int {
if num < 2 {
return 1
}
return fibonacci(num-1) + fibonacci(num-2)
}
當 執行這個應用時,帶了 cpuprofile 參數就可以記錄CPU到的Profile資訊。
testfibonacci.exe -cpuprofile=2.prof
我們隨後使用這個prof 資訊做效能分析圖了(需要安裝graphviz)
Graphviz 下載地址: http://www.graphviz.org/Download_windows.php
Graphviz 安裝完成後,需要把bin目錄放入 path 參數中。比如我這裡 win7下安裝目錄是: C:\Program Files (x86)\Graphviz2.38\bin 。
使用go tool pprof (應用程式) (應用程式的prof檔案) 我這裡是: go tool pprof testfibonacci.exe 2.prof
進入到pprof,使用web命令就會產生svg檔案,svg檔案是可以在瀏覽器下看的。像這個樣子:
這時候產生的 svg 映像如下:
net/http/pprof 的用法樣本:
我這裡以 gotour 為例, 我用的是這個中英文混排的版本: https://github.com/zhanming/go-tour-cn
修改 D:\mycodes\golang\src\github.com\zhanming\go-tour-cn\gotour.cn 這個目錄的 local.go 檔案, 在引入包時,增加下面一行代碼:
_ "net/http/pprof"
然後編譯執行這個網站,我們在訪問 http://localhost:3999/debug/pprof/ 時候,就可以看到下面資訊。
想要產生CPU狀態分析圖,調用go tool pprof http://localhost:3999/debug/pprof/profile
就會進入30秒的profile收集時間,在這段事件內猛重新整理點擊go-tour瀏覽器上的頁面,盡量讓cpu佔用效能產生資料。
使用 web 命令生產的圖如下:
有關go tool pprof 命令相關的內容可以參考:
https://github.com/hyper-carrot/go_command_tutorial/blob/master/0.12.md
它的主要命令如下:
表 pprof工具在互動模式下支援的命令
補充
如果你的go程式不是web伺服器,而是一個服務進程,那麼你也可以選擇使用net/http/pprof包,同樣引入包net/http/pprof,然後在開啟另外一個goroutine來開啟連接埠監聽。
比如:
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
參考資料:
Go的pprof使用
http://www.cnblogs.com/yjf512/archive/2012/12/27/2835331.html