python - 使用 pyo3 的 python 扩展不会提高速度

标签 python rust

我的环境

  • Ubuntu 18.04
  • Rust 1.36.0(每晚)
  • python 3.7.3

问题

我想用 Rust 写一个 python 扩展。我使用 PyO3 如下,

use pyo3::prelude::*;


#[pymodule(example)]
fn rust2py(py: Python, m: &PyModule) -> PyResult<()> {
     #[pyfn(m, "fib")]
     fn fib(_py: Python, n:i64) -> PyResult<i64> {
         let out = fib_rust(n);
         Ok(out)
     }

     Ok(())
}


fn fib_rust(n: i64) -> i64 {
      if n == 1 || n == 2 {
          return 1
      }

      fib_rust(n - 1) + fib_rust(n - 2)
}

我比较了 extension with rust 和 pure python 计算斐波那契数列的速度。我将这个程序构建为

cargo build --release

并复制当前目录下的.so文件。我用 python 中的时间库测量了耗时,但扩展和纯 python 之间几乎相同。

这个程序有什么问题。

最佳答案

正如 SOFe 所说,在简单的代码中,纯 python 和 rust 扩展之间的区别是微不足道的。当我在我的代码中放入 for 循环时,在 rust 扩展方面性能很高。

关于python - 使用 pyo3 的 python 扩展不会提高速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57941377/

相关文章:

python - 在 Python 中编写自定义矩阵类,__setitem__ 问题

python - 如何使用 Python - Gmail API 将大文件附加到电子邮件

haskell - 参数多态性和更高种类的类型之间有什么区别?

python - Plotly Express 如何展示图例?

python - 采用变量类型参数的类是否是糟糕的架构

rust - 有没有一种优雅的方法来重写使用 `match`语句获取或创建Option? [复制]

rust - 强制迭代器返回值而不是引用(反之亦然)的正确方法是什么?

rust - 运行 'rustup doc' 时拒绝访问

rust - 错误 : failed to run custom build command for `openssl v0.9.24`

python - 登录后django重定向不起作用 "next"没有发布?