如何在计数过程中提高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.

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.