Taking this documentation, I improperly wrote a function that calculates the power of a number in Rust, compiled it to a shared object and used it in Python. Then I have written the same algorithm with Python. I tested both and Python seems to be much faster.
sum.rs (it was supposed to sum, I changed my mind later)
#[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))
I have written and compiled Rust in the most primitive way (which means, without cargo
).This is how I compiled Rust code above:
rustc sum.rs --crate-type dylib
The results are as below:
1st Test
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
2nd Test
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
3rd Test
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
It seems that the same method runs much faster in Python. Why is that?
Update: Timing within Rust
I edited content of sum.rs
as below (added main function):
#[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);
}
Compiled it with:
rustc sum.rs
Then run it with time
in Linux, as below (after chmod +x ./sum
):
time -v ./sum
Test 1
real 0m2.035s
user 0m0.140s
sys 0m0.072s
Test 2
real 0m0.176s
user 0m0.128s
sys 0m0.040s
Test 3
real 0m0.184s
user 0m0.136s
sys 0m0.044s
With rustc -O
option
Compiled as below and given executable permission:
rustc -O sum.rs
Test 1
real 0m0.169s
user 0m0.132s
sys 0m0.032s
Test 2
real 0m0.207s
user 0m0.148s
sys 0m0.048s
Test 3
real 0m0.170s
user 0m0.124s
sys 0m0.040s
Environment
- Python 3.5.2
- Rust 1.7.0