虽然这个问题相当宽泛,但总的来说,是。它确实加快了代码的速度,有时甚至达到100。在
作为参考,Cython文档说我引用However, for performance critical code, it is often helpful to add static type declarations, as they will allow Cython to step out of the dynamic nature of the Python code and generate simpler and faster C code - sometimes faster by orders of magnitude< > C/C++语言的主要原因是它们创建了机器依赖的汇编语言来调整所有依赖硬件的优化。这是通过使用编译器来实现的,这主要是因为静态类型变量
循环展开
分支预测
等等。。在
现在Cython广泛使用静态类型变量的一个重要特性。由于python变量是无类型的,而C变量不是,Cython可以给用户提供静态修复变量类型的灵活性。在
在Cython docwebsite中,他们展示了仅仅通过提到类型就可以产生35%更快的性能。在
注意但是我最后要说的是,在用Cython转换Python代码时要小心,因为您可能在项目中使用了一些不支持Cython的框架/api。有时,即使你把你的代码转换成Cython,它也不会改变任何东西。一切都取决于你的代码。
因此,首先要确保Python中Python代码的完全可移植性,并检查是否绝对必要。
编辑1还有一点是,在Cython中转换代码会降低可读性,因此请注意这一点。在
再次引用Cython Docs的话It must be noted, however, that type declarations can make the source code more verbose and thus less readable. It is therefore discouraged to use them without good reason, such as where benchmarks prove that they really make the code substantially faster in a performance critical section
编辑2回答问题还是需要用cython重写代码才能真正看到改进?
不因为Cython编译器为您完成全部工作。在The Cython compiler will convert it into C code which makes equivalent calls to the Python/C API.
As Cython can accept almost any valid python source file, one of the hardest things in getting started is just figuring out how to compile your extension.
有关详细信息,请访问this