Can Go really be that much faster than Python?


I think I may have implemented this incorrectly because the results do not make sense. I have a Go program that counts to 1000000000:

package main

import (

func main() {
    for i := 0; i < 1000000000; i++ {}

It finishes in less than a second. On the other hand I have a Python script:

x = 0
while x < 1000000000:
print 'Done'

It finishes in a few minutes.

Why is the Go version so much faster? Are they both counting up to 1000000000 or am I missing something?

6/4/2019 11:27:58 PM

Accepted Answer

One billion is not a very big number. Any reasonably modern machine should be able to do this in a few seconds at most, if it's able to do the work with native types. I verified this by writing an equivalent C program, reading the assembly to make sure that it actually was doing addition, and timing it (it completes in about 1.8 seconds on my machine).

Python, however, doesn't have a concept of natively typed variables (or meaningful type annotations at all), so it has to do hundreds of times as much work in this case. In short, the answer to your headline question is "yes". Go really can be that much faster than Python, even without any kind of compiler trickery like optimizing away a side-effect-free loop.

9/25/2012 1:35:26 AM

pypy actually does an impressive job of speeding up this loop

def main():
    x = 0
    while x < 1000000000:

if __name__ == "__main__":
    print time.time() - s

$ python 
$ pypy 

~97% speedup!

Clarification for 3 people who didn't "get it". The Python language itself isn't slow. The CPython implementation is a relatively straight forward way of running the code. Pypy is another implementation of the language that does many tricky (especiallt the JIT) things that can make enormous differences. Directly answering the question in the title - Go isn't "that much" faster than Python, Go is that much faster than CPython.

Having said that, the code samples aren't really doing the same thing. Python needs to instantiate 1000000000 of its int objects. Go is just incrementing one memory location.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow