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

huangapple go评论85阅读模式
英文:

How to improve the speed of golang in a counting process?

问题

我有以下的golang代码:

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

当我运行它时,执行时间大约为26秒。

但对于下面的代码,它得到了相同的结果:

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

执行时间大约为13秒。为什么会这样?

在C++中,经过的时间是0秒。有什么建议可以提高golang的速度吗?

最好的问候。

英文:

I have the next golang code:

var c uint64;
for c = 1; c &lt;=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

得分: 5

首先,你需要确保循环的次数相同。将两个c变量声明为uint64类型。否则,c可能被声明为32位整数,会导致溢出。

package main

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

计时结果:

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

以及

package main

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

计时结果:

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

Go的计时结果是相等的。

C++优化会识别到循环是无意义的,因此不会执行它。

英文:

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 &lt;= 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.

huangapple
  • 本文由 发表于 2014年12月14日 06:28:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/27464302.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定