考虑到这个documentation,我不正确地编写了一个函数来计算Rust中数字的强大功能,将其编译为共享对象并在Python中使用它。然后我用Python编写了相同的算法。我测试了两者,Python看起来要快得多。
#[no_mangle]
pub extern fn powerof(a: i32, b: i32) -> i32 {
let mut c: i32 = a;
for x in 0..b {
c = c*a;
}
return c;
}
from ctypes import cdll
import time
_powerof = cdll.LoadLibrary("./libsum.so")
def timing(f):
# http://stackoverflow.com/a/5478448
def wrap(*args):
time1 = time.time()
ret = f(*args)
time2 = time.time()
print('{} function took {:0.4f} ms'.format(f.__name__, (time2-time1)*1000.0))
return ret
return wrap
@timing
def powerof(a, b):
global _powerof
result = _powerof.powerof(a, b)
return int(result)
@timing
def powerof_python(a, b):
c = a
for i in range(b):
c=c*a
return c
if __name__ == "__main__":
print(powerof(4,5))
print(powerof(2,3))
print(powerof(6,4))
print(powerof_python(4,5))
print(powerof_python(2,3))
print(powerof_python(6,4))
我用最原始的方式编写和编译了Rust (这意味着没有cargo
)。这就是我编译Rust代码的方法:
rustc sum.rs --crate-type dylib
结果如下:
powerof function took 0.0780 ms
4096
powerof function took 0.0136 ms
16
powerof function took 0.0064 ms
7776
powerof_python function took 0.0110 ms
4096
powerof_python function took 0.0041 ms
16
powerof_python function took 0.0050 ms
7776
powerof function took 0.0820 ms
4096
powerof function took 0.0083 ms
16
powerof function took 0.0057 ms
7776
powerof_python function took 0.0110 ms
4096
powerof_python function took 0.0041 ms
16
powerof_python function took 0.0041 ms
7776
powerof function took 0.0772 ms
4096
powerof function took 0.0098 ms
16
powerof function took 0.0069 ms
7776
powerof_python function took 0.0129 ms
4096
powerof_python function took 0.0036 ms
16
powerof_python function took 0.0043 ms
7776
似乎同样的方法在Python中运行得更快。那是为什么?
我编辑了以下sum.rs
的内容(添加了主要功能):
#[no_mangle]
pub extern fn powerof(a: i32, b: i32) -> i32 {
let mut c: i32 = a;
for x in 0..b {
c = c*a;
}
return c;
}
fn main() {
let a = powerof(4,5);
let b = powerof(2,3);
let c = powerof(6,4);
println!("{}",a);
println!("{}",b);
println!("{}",c);
}
编译:
rustc sum.rs
然后在Linux中使用time
运行它,如下所示(在chmod +x ./sum
之后):
time -v ./sum
real 0m2.035s
user 0m0.140s
sys 0m0.072s
real 0m0.176s
user 0m0.128s
sys 0m0.040s
real 0m0.184s
user 0m0.136s
sys 0m0.044s
rustc -O
选项编译如下并给出可执行权限:
rustc -O sum.rs
real 0m0.169s
user 0m0.132s
sys 0m0.032s
real 0m0.207s
user 0m0.148s
sys 0m0.048s
real 0m0.170s
user 0m0.124s
sys 0m0.040s