我有 2 种方法可以从子域中删除域后缀,我想找出哪种方法更快。我该怎么做?
最佳答案
您可以使用内置的 benchmark capabilities的 go test
.
例如 ( on play ):
import (
"strings"
"testing"
)
func BenchmarkStrip1(b *testing.B) {
for br := 0; br < b.N; br++ {
host := "subdomain.domain.tld"
s := strings.Index(host, ".")
_ = host[:s]
}
}
func BenchmarkStrip2(b *testing.B) {
for br := 0; br < b.N; br++ {
host := "subdomain.domain.tld"
strings.TrimSuffix(host, ".domain.tld")
}
}
将此代码存储在 somename_test.go
中并运行 go test -test.bench='.*'
。对我来说,这给了
以下输出:
% go test -test.bench='.*'
testing: warning: no tests to run
PASS
BenchmarkStrip1 100000000 12.9 ns/op
BenchmarkStrip2 100000000 16.1 ns/op
ok 21614966 2.935s
基准实用程序将 attempt to do a certain number of runs直到一个有意义的时间
测量值反射(reflect)在输出中的数字 100000000
。代码已运行
100000000
次,循环中的每个操作分别花费 12.9 ns 和 16.1 ns。
因此您可以得出结论,BenchmarkStrip1
中的代码性能更好。
无论结果如何,profile your program 往往更好看看在哪里 真正的瓶颈是不要将时间浪费在这些微基准测试上。
我也不建议您编写自己的基准测试,因为您可能会遇到一些因素 不考虑诸如the garbage collector和 running your samples long enough .
关于go - 我如何找出两种方法中哪一种更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21614966/