首页 > 解决方案 > 使用 pyo3 的 python 扩展没有提高速度

问题描述

我的环境

问题

我想用 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)
}

我比较了使用 rust 和纯 python 扩展计算斐波那契数列的速度。我将此程序构建为

cargo build --release

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

这个程序有什么问题。

标签: pythonrust

解决方案


As SOFe said, in simple code, the difference between pure python and rust extension is ignoble. When I put for loop in my code, the performance was high in extension with rust.


推荐阅读