为什么 Python 程序通常比用 C 或 C++ 编写的等效程序慢? [英] Why are Python Programs often slower than the Equivalent Program Written in C or C++?

查看:39
本文介绍了为什么 Python 程序通常比用 C 或 C++ 编写的等效程序慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 Python 平均起来比 C/C++ 慢?我学习 Python 作为我的第一门编程语言,但我才刚刚开始学习 C,我已经感觉到我可以看到明显的不同.

Why does Python seem slower, on average, than C/C++? I learned Python as my first programming language, but I've only just started with C and already I feel I can see a clear difference.

推荐答案

Python 是比 C 更高级的语言,这意味着它从你那里抽象出计算机的细节——内存管理、指针等,并允许你编写以更接近人类思维方式的方式编程.

Python is a higher level language than C, which means it abstracts the details of the computer from you - memory management, pointers, etc, and allows you to write programs in a way which is closer to how humans think.

如果仅衡量执行时间,C 代码的运行速度通常比 Python 代码快 10 到 100 倍,这是事实.但是,如果您还包括开发时间,Python 通常会击败 C.对于许多项目而言,开发时间远比运行时性能更重要.更长的开发时间直接转化为额外的成本、更少的功能和更慢的上市时间.

It is true that C code usually runs 10 to 100 times faster than Python code if you measure only the execution time. However if you also include the development time Python often beats C. For many projects the development time is far more critical than the run time performance. Longer development time converts directly into extra costs, fewer features and slower time to market.

Python 代码执行速度较慢的内部原因是代码在运行时被解释,而不是在编译时被编译为本机代码.

Internally the reason that Python code executes more slowly is because code is interpreted at runtime instead of being compiled to native code at compile time.

其他解释型语言(例如 Java 字节码和 .NET 字节码)的运行速度比 Python 快,因为标准发行版包括 JIT 编译器 在运行时将字节码编译为本机代码.CPython 还没有 JIT 编译器的原因是因为 Python 的动态特性使其难以编写.工作progress 编写更快的 Python 运行时,因此您应该期望将来性能差距会缩小,但在标准 Python 之前可能需要一段时间发行版包括一个强大的 JIT 编译器.

Other interpreted languages such as Java bytecode and .NET bytecode run faster than Python because the standard distributions include a JIT compiler that compiles bytecode to native code at runtime. The reason why CPython doesn't have a JIT compiler already is because the dynamic nature of Python makes it difficult to write one. There is work in progress to write a faster Python runtime so you should expect the performance gap to be reduced in the future, but it will probably be a while before the standard Python distribution includes a powerful JIT compiler.

这篇关于为什么 Python 程序通常比用 C 或 C++ 编写的等效程序慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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