gpt4 book ai didi

go - 我如何找出两种方法中哪一种更快?

转载 作者:IT王子 更新时间:2023-10-29 00:59:59 26 4
gpt4 key购买 nike

我有 2 种方法可以从子域中删除域后缀,我想找出哪种方法更快。我该怎么做?

2 string trimming methods

最佳答案

您可以使用内置的 benchmark capabilitiesgo 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 collectorrunning your samples long enough .

关于go - 我如何找出两种方法中哪一种更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21614966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com