2016-03-08 34 views
5

我嘗試分析我的go庫,找出在C++中比同類事物慢得多的原因。Golang分析 - top10只顯示一行100%

我簡單的基準

func BenchmarkFile(t *testing.B) { 
    tmpFile, err := ioutil.TempFile("", TMP_FILE_PREFIX) 

    fw, err := NewFile(tmpFile.Name()) 
    text := []byte("testing") 
    for i := 0; i < b.N; i++ { 
     _, err = fw.Write(text) 
    } 
    fw.Close() 
} 

NEWFILE返回編碼數據,我們的二進制表示我自定義的作家,甚至對其進行壓縮,並寫入文件系統。

運行go test -bench . -memprofile mem.out -cpuprofile cpu.out我得到

PASS 
BenchmarkFile-16 2000000000   0.20 ns/op 
ok  .../writer/iowriter 9.074s 

不是分析

# go tool pprof cpu.out 
Entering interactive mode (type "help" for commands) 
(pprof) top10 
930ms of 930ms total ( 100%) 
     flat flat% sum%  cum cum% 
    930ms 100% 100%  930ms 100% 
(pprof) 

我甚至嘗試寫這是用我的作家example.go的應用程序,並在http://blog.golang.org/profiling-go-programs但顯示添加pprof.StartCPUProfile(f)相同的結果。

我在做什麼錯,我怎樣才能確定什麼是我的lib的瓶頸? 預先感謝您

+2

爲什麼使用「i <1000」?基準測試必須使用b.N字段,否則他們不會給出正確的結果,因爲每個基準測試函數都可能被多次調用b.N.的不同值。 – nussjustin

+0

好的,我會修復 – sejvlond

回答

7

好很容易,我想補充的二進制去工具pprof,對那一定是

# go tool pprof write cpu.out 
Entering interactive mode (type "help" for commands) 
(pprof) top10 
7.02s of 7.38s total (95.12%) 
Dropped 14 nodes (cum <= 0.04s) 
Showing top 10 nodes out of 32 (cum >= 0.19s) 
     flat flat% sum%  cum cum% 
    6.55s 88.75% 88.75%  6.76s 91.60% syscall.Syscall 
    ... 

和使用基準測試時,二進制創建那裏,並用它給同結果。

+1

你能澄清這個答案嗎?目前還不清楚你的解決方案是否有效或是否有效。 – Dan

+0

我認爲這很清楚。 「我錯過了添加二進制工具pprof」 ,所以它必須是:「去工具pprof寫cpu.out」 和此命令後,你可以看到輸出,所以它的工作.. – sejvlond

+0

對於那些想知道,「寫「是二進制文件的名稱。 –

0

要擴大sejvolnd的回答是:

pprof需要的是實際產生cpu.out文件作爲第一個參數的二進制文件。

所以,你需要爲go tool pprof <go binary of your program> <generaged profiling output file>

例如運行命令go tool pprof go_binary cpu.pprof