英文:
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 <=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 <= 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论