Go真的可以比Python快得多吗? [英] Can Go really be that much faster than Python?

查看:72
本文介绍了Go真的可以比Python快得多吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我可能执行不正确,因为结果没有意义.我有一个转到1000000000的Go程序:

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") 
}

它在不到一秒钟的时间内完成.另一方面,我有一个Python脚本:

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'

几分钟后完成.

为什么Go版本的速度这么快?他们俩都算上了10亿吗?还是我想念什么?

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

推荐答案

十亿不是一个很大的数字.如果它能够使用本机类型,那么任何相当现代的计算机 最多都可以在几秒钟内完成此操作.我通过编写一个等效的C程序,读取程序集以确保它确实在进行加法并计时(在我的计算机上约1.8秒内完成)来验证这一点.

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没有本机类型变量(或根本没有有意义的类型注释)的概念,因此在这种情况下,它必须完成数百倍的工作.简而言之,您对标题问题的回答是是".即使没有像优化无副作用循环之类的任何编译器技巧,Go 真的可以比Python快得多.

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.

这篇关于Go真的可以比Python快得多吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆