dtny30176 2012-09-25 01:00
浏览 378
已采纳

Go真的可以比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 (
    "fmt"
)

func main() {
    for i := 0; i < 1000000000; i++ {}
    fmt.Println("Done") 
}

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

x = 0
while x < 1000000000:
    x+=1
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?

  • 写回答

8条回答 默认 最新

  • doulingzhuang3079 2012-09-25 01:35
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?