python - 使用 pyo3 的 python 扩展没有提高速度
问题描述
我的环境
- 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)
}
我比较了使用 rust 和纯 python 扩展计算斐波那契数列的速度。我将此程序构建为
cargo build --release
并在当前目录中复制.so
文件。我用python中的时间库测量了经过的时间,但这在扩展和纯python之间几乎相同。
这个程序有什么问题。
解决方案
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.
推荐阅读
- assembly - 程序集是特定于 CPU、CPU 架构还是其他什么?
- python - Python Tkinter 文本插入方法
- c# - 在 Visual Studio 2017 上检查非托管 C++ 对象/变量
- python - 如何在 cog discordpy 中卸载命令?
- asp.net-core - XUnit ASP.Net Core WebAPI 测试中 EnsureSuccessStatusCode 和 Assert.Equal(HttpStatusCode.OK, response.StatusCode) 之间的区别
- python - 如何在两个脚本中以大写字母拆分字符串
- bash - 如果后台进程之一在 bash 中失败,如何使整个主进程失败?
- javascript - 在 JS 中无法使用键名访问 JSON 对象值
- angular - Angular:PrimeNG 组织结构图未正确呈现图表
- html - 如何在 react 中使用 css 拉伸我的背景?(处理溢出)