Skip to content

Instantly share code, notes, and snippets.

@erayerdin
Created November 19, 2016 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erayerdin/33b6713453dd5e4c530ac1074012b8f0 to your computer and use it in GitHub Desktop.
Save erayerdin/33b6713453dd5e4c530ac1074012b8f0 to your computer and use it in GitHub Desktop.
Test of Rust in Python with ctypes

Abstract

I did a test to read a SO with ctypes in Python, which is compiled with Rust. I wanted to write a function in both languages and measure their timing. These functions will calculate the b power of a. Pseudocode for algorithm is as below:

fn power(int a, int b) -> int {
    int c = a
    for b times {
        c = c*a;
    }
    return c;
}

Build Manual

rustc power.rs --crate-type dylib

Test Environment

  • An old computer
  • Python 3.5.2
  • rustc 1.7.0
#[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("./libpower.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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment