您好,登錄后才能下訂單哦!
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 ?????????} ??????} ???} }
執(zhí)行命令: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
查看更多內(nèi)容
原文:
https://www.jianshu.com/p/d276aa7300d1
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。