問題描述
為什么 Python 平均起來比 C/C++ 慢?我學(xué)習(xí) Python 作為我的第一門編程語言,但我才剛剛開始學(xué)習(xí) C,我已經(jīng)感覺到我可以看到明顯的不同.
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 更高級(jí)的語言,這意味著它從你那里抽象出計(jì)算機(jī)的細(xì)節(jié)——內(nèi)存管理、指針等,并允許你編寫以更接近人類思維方式的方式編程.
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.
如果僅衡量執(zhí)行時(shí)間,C 代碼的運(yùn)行速度通常比 Python 代碼快 10 到 100 倍,這是事實(shí).但是,如果您還包括開發(fā)時(shí)間,Python 通常會(huì)擊敗 C.對(duì)于許多項(xiàng)目而言,開發(fā)時(shí)間遠(yuǎn)比運(yùn)行時(shí)性能更重要.更長的開發(fā)時(shí)間直接轉(zhuǎn)化為額外的成本、更少的功能和更慢的上市時(shí)間.
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 代碼執(zhí)行速度較慢的內(nèi)部原因是代碼在運(yùn)行時(shí)被解釋,而不是在編譯時(shí)被編譯為本機(jī)代碼.
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 字節(jié)碼和 .NET 字節(jié)碼)的運(yùn)行速度比 Python 快,因?yàn)闃?biāo)準(zhǔn)發(fā)行版包括 JIT 編譯器 在運(yùn)行時(shí)將字節(jié)碼編譯為本機(jī)代碼.CPython 還沒有 JIT 編譯器的原因是因?yàn)?Python 的動(dòng)態(tài)特性使其難以編寫.工作在progress 編寫更快的 Python 運(yùn)行時(shí),因此您應(yīng)該期望將來性能差距會(huì)縮小,但在標(biāo)準(zhǔn) Python 之前可能需要一段時(shí)間發(fā)行版包括一個(gè)強(qiáng)大的 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.
這篇關(guān)于為什么 Python 程序通常比用 C 或 C++ 編寫的等效程序慢?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!