为什么用Rust编译的共享对象库使用ctypes运行速度较慢?

时间:2016-11-18 19:02:40

标签: python rust ctypes

考虑到这个documentation,我不正确地编写了一个函数来计算Rust中数字的强大功能,将其编译为共享对象并在Python中使用它。然后我用Python编写了相同的算法。我测试了两者,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;
}

trial.py

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中运行得更快。那是为什么?

更新:Rust中的时间

我编辑了以下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

测试1

real    0m2.035s
user    0m0.140s
sys     0m0.072s

测试2

real    0m0.176s
user    0m0.128s
sys     0m0.040s

测试3

real    0m0.184s
user    0m0.136s
sys     0m0.044s

使用rustc -O选项

编译如下并给出可执行权限:

rustc -O sum.rs

测试1

real    0m0.169s
user    0m0.132s
sys     0m0.032s

测试2

real    0m0.207s
user    0m0.148s
sys     0m0.048s

测试3

real    0m0.170s
user    0m0.124s
sys     0m0.040s

环境

  • Python 3.5.2
  • Rust 1.7.0

0 个答案:

没有答案