2013-04-23 74 views
26

在我的Go包中有幾個基準文件,如map1_benchmark_test.gomap2_benchmark_test.go。在每個*_benchmark_test.go文件中,都有多個基準函數,如func BenchmarkMapTravel(b *testing.B)func BenchmarkMapGet(b *testing.B)如何測試只有一個基準測試功能?

問題是,我該如何測試一個基準測試函數?

我試圖閱讀一些手冊,並通過運行go help test沒有得到任何有關基準。

回答

45

Description of testing flags

-test.bench pattern 
    Run benchmarks matching the regular expression. 
    By default, no benchmarks run. 

-test.run pattern 
    Run only those tests and examples matching the regular 
    expression. 

爲了方便起見,每個測試二進制的這些-test.X標誌是 也可作爲在 'go test' 本身的標誌-X

有關幫助信息,

$ go help testflag 

例如,

go test -test.bench MapTravel 
go test -test.bench MapGet 

go test -bench MapTravel 
go test -bench MapGet 

要繞過測試功能,包括-test.run圖案濾掉每一個測試。例如,

go test -test.bench MapTravel -test.run=thisexpressionwontmatchanytest 

go test -bench MapTravel -run=^$ 
+3

只有一個基準測試運行,但其他測試mehonds像'FUNC TestMapGet(T * testing.T)'不屬於基準測試過。那麼,如何在沒有其他測試運行的情況下運行基準測試? – hardPass 2013-04-23 06:15:36

+0

看到我修改的答案。 – peterSO 2013-04-23 06:34:13

+5

請注意,您不需要標記中的'test.'前綴,您可以只寫'go test -bench MapGet -run XXX',這樣稍微羅嗦一點就可以輸入。 (從文檔:爲方便起見,測試二進制文件中的每個'-test.X'標誌也可以在'go test'本身作爲標誌'-X'使用。) – 2013-04-23 06:55:19

0

測試僅TestFuncOne

$>> go test -run TestFuncOne 

stuff_to_test.go

TestFuncOne() { 
} 

TestFuncTwo() { 
} 
2

沒有可以提供的標誌,只能運行基準(或只有一個基準)。所述only flags related這些是:

-bench的regexp 運行基準匹配正則表達式。 默認情況下,不運行基準測試。要運行所有基準, 使用'-bench'。或'-bench ='。

-run正則表達式 僅運行與常規 表達式匹配的那些測試和示例。

所以,如果你想只運行一個標杆,你可以這樣做:

go test -bench=nameOfYourBenchmark -run=^a 

這將導致只運行與a開始測試。並且因爲每個測試應該被命名爲Test<something>,所以不會有測試運行。

只運行基準測試:

go test -bench=. -run=^a