普通网友 2014-02-06 21:59
浏览 39
已采纳

如何找出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条回答 默认 最新

  • douliao5942 2014-02-06 22:06
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)