如何确定两种方法中哪种更快?

huangapple go评论100阅读模式
英文:

How do I find out which of 2 methods is faster?

问题

我有两种方法可以从子域名中删除域名后缀,我想知道哪一种方法更快。我该如何做到这一点?

2个字符串修剪方法

英文:

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?

2 string trimming methods

答案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 (
	&quot;strings&quot;
	&quot;testing&quot;
)


func BenchmarkStrip1(b *testing.B) {
	for br := 0; br &lt; b.N; br++ {
		host := &quot;subdomain.domain.tld&quot;

		s := strings.Index(host, &quot;.&quot;)
		_ = host[:s]
	}
}

func BenchmarkStrip2(b *testing.B) {
	for br := 0; br &lt; b.N; br++ {
		host := &quot;subdomain.domain.tld&quot;

		strings.TrimSuffix(host, &quot;.domain.tld&quot;)
	}
}

Store this code in somename_test.go and run go test -test.bench=&#39;.*&#39;. For me this gives
the following output:

% go test -test.bench=&#39;.*&#39;
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.

huangapple
  • 本文由 发表于 2014年2月7日 05:59:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/21614966.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定