2017-05-09 27 views
4

時間值我已經在去寫一個基準我的國際象棋引擎:圍棋:使用的基準

func BenchmarkStartpos(b *testing.B) { 
    board := ParseFen(startpos) 
    for i := 0; i < b.N; i++ { 
     Perft(&board, 5) 
    } 
} 

我看到這個輸出,當它運行:

goos: darwin 
goarch: amd64 
BenchmarkStartpos-4   10  108737398 ns/op 
PASS 
ok  _/Users/dylhunn/Documents/go-chess 1.215s 

我想用的時候每次執行(在這種情況下,108737398 ns/op)來計算另一個值,並將其作爲基準的結果打印出來。具體來說,我想輸出節點每秒,這是Perft呼叫的結果除以每次呼叫的時間。

如何訪問基準執行的時間,以便我可以打印自己的派生結果?

回答

8

您可以使用testing.Benchmark()功能來手動測量/基準「基準」功能(即有func(*testing.B)簽名),你得到的結果作爲testing.BenchmarkResult值,這是你需要的所有細節的結構:

type BenchmarkResult struct { 
    N   int   // The number of iterations. 
    T   time.Duration // The total time taken. 
    Bytes  int64   // Bytes processed in one iteration. 
    MemAllocs uint64  // The total number of memory allocations. 
    MemBytes uint64  // The total number of bytes allocated. 
} 

每次執行的時間由BenchmarkResult.NsPerOp()方法返回,你可以做任何你想做的這一點。

參見這個簡單的例子:

func main() { 
    res := testing.Benchmark(BenchmarkSleep) 
    fmt.Println(res) 
    fmt.Println("Ns per op:", res.NsPerOp()) 
    fmt.Println("Time per op:", time.Duration(res.NsPerOp())) 
} 

func BenchmarkSleep(b *testing.B) { 
    for i := 0; i < b.N; i++ { 
     time.Sleep(time.Millisecond * 12) 
    } 
} 

的輸出被(嘗試在Go Playground):

 100  12000000 ns/op 
Ns per op: 12000000 
Time per op: 12ms 
+0

由於該溶液含有'主()'函數,它必須被放置在一個「主」包,對嗎?我的項目是一個圖書館,因此沒有主要的軟件包,並且向回購商添加一個會導致人們通過'go get'獲取它的困難。有什麼解決方法嗎? – dylhunn

+0

@dylhunn我包含一個指向[Go Playground](https://play.golang.org/p/0Rf_y1vNUp)的鏈接,您可以在其中嘗試它。有一個'main()'函數就是你可以試用它的方式。你可以使用'main()'函數中的代碼_everywhere_,顯然也包括非'main'函數,也包括測試包。 – icza

+0

@ixza啊,我明白了。謝謝您的幫助! – dylhunn