【发布时间】:2022-11-12 17:18:32
【问题描述】:
我正在尝试使用 py03 的 rust 绑定来加速一些 python 代码。
我在 python 和 rust 中实现了以下功能:
def _play_action(state, action):
temp = state.copy()
i1, j1, i2, j2 = action
h1 = abs(temp[i1][j1])
h2 = abs(temp[i2][j2])
if temp[i1][j1] < 0:
temp[i2][j2] = -(h1 + h2)
else:
temp[i2][j2] = h1 + h2
temp[i1][j1] = 0
return temp
#[pyfunction]
fn play_action(state: [[i32; 9]; 9], action : [usize;4]) -> [[i32; 9]; 9] {
let mut s = state.clone();
let h1 = s[action[0]][action[1]];
let h2 = s[action[2]][action[3]];
s[action[0]][action[1]] = 0;
s[action[2]][action[3]] = h1.signum() * (h1 + h2).abs();
s
令我惊讶的是,python 版本更快……知道为什么吗?
【问题讨论】:
-
您是否使用 --release 进行编译,是否可以通过使用
mut state参数来避免let mut s = state.clone();? -
这段代码做的并不多,这会花费时间。与函数实际执行的操作相比,从 python 调用 rust 函数的开销可能太高。
标签: python performance rust