doujia2463 2014-12-13 22:28
浏览 35
已采纳

如何在计数过程中提高golang的速度?

I have the next golang code:

var c uint64;
for c = 1; c <=10000000000 ; c++ { }

When I run it, the execution time is about 26 seconds.

But for the next code that gets the same result:

c = 0
for {
    c++
    if c == 10000000000 {
       break
    }
}

the execution time is about 13 seconds. Why is that?

In C++ the elapsed time is 0 seconds. Any suggestion to improve the speed in golang?

Best regards.

  • 写回答

1条回答 默认 最新

  • dpd3982 2014-12-13 22:44
    关注

    First, you need to make sure that that you are looping the same number of times. Declare both c variables as uint64. Otherwise, c may be declared as 32 bit integer which will overflow.

    package main
    
    func main() {
        var c uint64
        for c = 1; c <= 10000000000; c++ {
        }
    }
    

    Timing:

    real    0m5.371s
    user    0m5.374s
    sys 0m0.000s
    

    and

    package main
    
    func main() {
        var c uint64
        for {
            c++
            if c == 10000000000 {
                break
            }
        }
    }
    

    Timing:

    real    0m5.443s
    user    0m5.442s
    sys 0m0.004s
    

    The Go timings are equal.

    C++ optimization recognizes that the loop is pointless so it doesn't execute it.

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

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b