是什么使C比Python快? [英] What makes C faster than Python?

查看:54
本文介绍了是什么使C比Python快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这可能是一个非常明显的答案,而且我正在向自己提供一些不太有用的过时的评论,但我不知道答案是什么.

I know this is probably a very obvious answer and that I'm exposing myself to less-than-helpful snarky comments, but I don't know the answer so here goes.

如果Python在运行时编译为字节码,是否只是花费较长时间的初始编译步骤?如果是这种情况,那不只是代码中的一小笔前期成本(即,如果代码运行时间较长,那么C和python之间的差异是否会减小?)

If Python compiles to bytecode at runtime, is it just that initial compiling step that takes longer? If that's the case wouldn't that just be a small upfront cost in the code (ie if the code is running over a long period of time, do the differences between C and python diminish?)

推荐答案

这不仅解释了Python代码,而且使它变慢,尽管这确实限制了获取速度的限制.

It's not merely the fact that Python code is interpreted which makes it slower, although that definitely sets a limit to how fast you can get.

如果以字节码为中心的观点正确,那么要使Python代码像C一样快,您要做的就是用直接调用函数替换解释器循环,消除任何字节码,然后编译结果代码.但这不是那样的.您也不必信服我:您可以自己测试.Cython将Python代码转换为C,但是转换后再编译的典型Python函数不会显示C级速度.您所要做的就是查看由此产生的一些典型的C代码,以了解原因.

If the bytecode-centric perspective were right, then to make Python code as fast as C all you'd have to do is replace the interpreter loop with direct calls to the functions, eliminating any bytecode, and compile the resulting code. But it doesn't work like that. You don't have to take my word for it, either: you can test it for yourself. Cython converts Python code to C, but a typical Python function converted and then compiled doesn't show C-level speed. All you have to do is look at some typical C code thus produced to see why.

真正的挑战是多重派遣(或正确的行话是什么,我不能保持直截了当),这意味着一个事实,而 a + b 如果a b 都是整数,或者浮点数可以编译成C语言中的一个op,在Python中,您必须做更多的工作才能计算出 a + b (获取名称绑定到的对象,通过 __ add __ 等)

The real challenge is multiple dispatch (or whatever the right jargon is -- I can't keep it all straight), by which I mean the fact that whereas a+b if a and b are both known to be integers or floats can compile down to one op in C, in Python you have to do a lot more to compute a+b (get the objects that the names are bound to, go via __add__, etc.)

这就是为什么要使Cython达到C速度,您必须在关键路径中指定类型;这就是Shedskin如何使用(笛卡尔积)类型推断使Python代码快速实现的,从而使C ++脱颖而出.以及PyPy的运行速度如何-JIT可以关注代码的行为方式并专门研究类型(type)之类的东西.每种方法都消除了动态性,无论是在编译时还是在运行时,都可以生成知道其工作方式的代码.

This is why to make Cython reach C speeds you have to specify the types in the critical path; this is how Shedskin makes Python code fast using (Cartesian product) type inference to get C++ out of it; and how PyPy can be fast -- the JIT can pay attention to how the code is behaving and specialize on things like types. Each approach eliminates dynamism, whether at compile time or at runtime, so that it can generate code which knows what it's doing.

这篇关于是什么使C比Python快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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