duangou1953 2017-11-17 19:50
浏览 10
已采纳

简单计算基准的基本解释

The following benchmarks performs best on the one with a function operating the calculation. Even if it inlines, why does it perform better?

func add1(i int) int {
    return i + 1
}

var x = 0

func BenchmarkAdd1(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x = x + 1
    }
}

func BenchmarkAdd1ForceType(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x = x + int(1)
    }
}

func BenchmarkIncrement(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x++
    }
}

func BenchmarkAdd1WithFunction(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x = add1(x)
    }
}


 BenchmarkAdd1-8                         1000000000               1.99 ns/op
 BenchmarkAdd1ForceType-8                2000000000               1.96 ns/op
 BenchmarkIncrement-8                    2000000000               2.02 ns/op
 BenchmarkAdd1WithFunction-8             2000000000               0.44 ns/op

CPU is Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz

Go version 1.9.2 darwin/amd64

  • 写回答

1条回答 默认 最新

  • duanou1904 2017-11-17 19:57
    关注

    It gets optimized away. If you do something with x after the loop, you'll find they all perform about the same:

    var buf = new(bytes.Buffer)
    
    func add1(i int) int {
        return i + 1
    }
    
    func BenchmarkAdd1(b *testing.B) {
        var x = 0
        for i := 0; i < b.N; i++ {
            x = x + 1
        }
        fmt.Fprintln(buf, x)
    }
    
    func BenchmarkAdd1ForceType(b *testing.B) {
        var x = 0
        for i := 0; i < b.N; i++ {
            x = x + int(1)
        }
        fmt.Fprintln(buf, x)
    }
    
    func BenchmarkIncrement(b *testing.B) {
        var x = 0
        for i := 0; i < b.N; i++ {
            x++
        }
        fmt.Fprintln(buf, x)
    }
    
    func BenchmarkAdd1WithFunction(b *testing.B) {
        var x = 0
        for i := 0; i < b.N; i++ {
            x = add1(x)
        }
        fmt.Fprintln(buf, x)
    }
    

    This yields:

    BenchmarkAdd1-4                 2000000000           0.34 ns/op
    BenchmarkAdd1ForceType-4        2000000000           0.33 ns/op
    BenchmarkIncrement-4            2000000000           0.34 ns/op
    BenchmarkAdd1WithFunction-4     2000000000           0.35 ns/op
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持