英文:
How do I find out which of 2 methods is faster?
问题
我有两种方法可以从子域名中删除域名后缀,我想知道哪一种方法更快。我该如何做到这一点?
英文:
I have 2 methods to trim the domain suffix from a subdomain and I'd like to find out which one is faster. How do I do that?
答案1
得分: 5
你可以使用内置的go test
的基准测试功能。
例如(在playground上):
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
基准测试工具将尝试运行一定数量的次数,直到测量到有意义的时间,这通过数字100000000
在输出中反映出来。代码被运行了100000000
次,循环中的每个操作分别花费了12.9 ns和16.1 ns。因此,你可以得出结论,BenchmarkStrip1
中的代码表现更好。
无论结果如何,通常最好的做法是对程序进行性能分析,以查看真正的瓶颈在哪里,而不是浪费时间进行这些微基准测试。
我也不建议编写自己的基准测试,因为有一些因素你可能没有考虑到,比如垃圾回收器和足够长时间运行样本。
英文:
You can use the builtin benchmark capabilities of go test
.
For example (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")
}
}
Store this code in somename_test.go
and run go test -test.bench='.*'
. For me this gives
the following output:
% 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
The benchmark utility will attempt to do a certain number of runs until a meaningful time is
measured which is reflected in the output by the number 100000000
. The code was run
100000000
times and each operation in the loop took 12.9 ns and 16.1 ns respectively.
So you can conclude that the code in BenchmarkStrip1
performed better.
Regardless of the outcome, it is often better to profile your program to see where the
real bottleneck is instead of wasting your time with micro benchmarks like these.
I would also not recommend writing your own benchmarking as there are some factors you might
not consider such as the garbage collector and running your samples long enough.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论