Can Go really be that much faster than Python?

前端 未结 8 1409
抹茶落季
抹茶落季 2021-01-31 14:27

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 (
             


        
相关标签:
8条回答
  • 2021-01-31 15:16

    It is possible that the compiler realized that you didn't use the "i" variable after the loop, so it optimized the final code by removing the loop.

    Even if you used it afterwards, the compiler is probably smart enough to substitute the loop with

    i = 1000000000;
    

    Hope this helps =)

    0 讨论(0)
  • 2021-01-31 15:20

    You've got two things at work here. The first of which is that Go is compiled to machine code and run directly on the CPU while Python is compiled to bytecode run against a (particularly slow) VM.

    The second, and more significant, thing impacting performance is that the semantics of the two programs are actually significantly different. The Go version makes a "box" called "x" that holds a number and increments that by 1 on each pass through the program. The Python version actually has to create a new "box" (int object) on each cycle (and, eventually, has to throw them away). We can demonstrate this by modifying your programs slightly:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        for i := 0; i < 10; i++ {
            fmt.Printf("%d %p\n", i, &i)
        }
    }
    

    ...and:

    x = 0;
    while x < 10:
        x += 1
        print x, id(x)
    

    This is because Go, due to it's C roots, takes a variable name to refer to a place, where Python takes variable names to refer to things. Since an integer is considered a unique, immutable entity in python, we must constantly make new ones. Python should be slower than Go but you've picked a worst-case scenario - in the Benchmarks Game, we see go being, on average, about 25x times faster (100x in the worst case).

    You've probably read that, if your Python programs are too slow, you can speed them up by moving things into C. Fortunately, in this case, somebody's already done this for you. If you rewrite your empty loop to use xrange() like so:

    for x in xrange(1000000000):
        pass
    print "Done."
    

    ...you'll see it run about twice as fast. If you find loop counters to actually be a major bottleneck in your program, it might be time to investigate a new way of solving the problem.

    0 讨论(0)
提交回复
热议问题