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

标签 go profiling

我有 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/

相关文章:

json - 如何在 Go 中进行嵌套的 JSON 响应?

go - 访问 C 联合字段时出现问题

python - Python 2.7 中有什么类似于 Go 的 `time.Tick` 或 Netty 的 `HashedWheelTimer` 吗?

html - 如何使用goquery提取自定义html标签的文本?

linux - pstack 作为分析工具的可靠性如何?

c - ocilib 的稳定性如何

java - @Profile 与 @ConditionalOnProperty

go - Go 中互斥体需要初始化吗?

c - 分析 u-Boot/内核启动顺序

android - 我如何分析内存和 cpu 虎钳的设备,以确定重型图像处理的图像分辨率?