您好,登錄后才能下訂單哦!
package?main import?( ???"testing" ) //?第一種 func?BenchmarkMake(t?*testing.B)?{ ???t.ResetTimer() ???origin?:=?[]int{1,?2,?3,?4,?5,?6,?7,?8,?9,?10} ???for?i?:=?0;?i?<?t.N;?i++?{ ??????target?:=?make([]int,?len(origin)) ??????for?_,?item?:=?range?origin?{ ?????????if?item?!=?6?{ ????????????target?=?append(target,?item) ?????????} ??????} ???} } //?第二種 func?BenchmarkReuse(t?*testing.B)?{ ???t.ResetTimer() ???origin?:=?[]int{1,?2,?3,?4,?5,?6,?7,?8,?9,?10} ???for?i?:=?0;?i?<?t.N;?i++?{ ??????target?:=?origin[:0] ??????for?_,?item?:=?range?origin?{ ?????????if?item?!=?6?{ ????????????target?=?append(target,?item) ?????????} ??????} ???} } //?第三種 func?BenchmarkEditOne(t?*testing.B)?{ ???t.ResetTimer() ???origin?:=?[]int{1,?2,?3,?4,?5,?6,?7,?8,?9,?10} ???for?i?:=?0;?i?<?t.N;?i++?{ ??????for?i?:=?0;?i?<?len(origin);?i++?{ ?????????if?origin[i]?==?6?{ ????????????origin?=?append(origin[:i],?origin[i+1:]...) ????????????i--?//?maintain?the?correct?index ?????????} ??????} ???} } //?第四種 func?BenchmarkFuck(t?*testing.B)?{ ???t.ResetTimer() ???origin?:=?[]int{1,?2,?3,?4,?5,?6,?7,?8,?9,?10} ???for?i?:=?0;?i?<?t.N;?i++?{ ??????for?i?:=?0;?i?<?len(origin);?i++?{ ?????????if?origin[i]?==?6?{ ????????????tempV?:=?origin[i] ????????????origin?=?append(append(origin[:i],?origin[i+1:]...),?tempV) ????????????//i--?//?maintain?the?correct?index ?????????} ??????} ???} }
執行命令:go test main6_test.go -v -bench=.
輸出:
E:\go_work_dir\test\x>go test main6_test.go -v -bench=.
goos: windows
goarch: amd64
BenchmarkMake-8???????? 10000000?????????????? 146 ns/op
BenchmarkReuse-8??????? 100000000?????????????? 10.9 ns/op
BenchmarkEditOne-8????? 200000000??????????????? 7.69 ns/op
BenchmarkFuck-8???????? 100000000?????????????? 13.4 ns/op
PASS
ok????? command-line-arguments? 8.592s
命令:go test main6_test.go -v -bench=. -benchtime=3s -benchmem
查看更多內容
原文:
https://www.jianshu.com/p/d276aa7300d1
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。