Python2.6 0.14
Python2.6 CTypes 0.71
Python2.7 0.15
Python2.7 CTypes 0.77
Python3.3 0.14
Python3.3 CTypes 0.71
PyPy 0.03
PyPy CTypes 0.22
Jython doesn't support ctypes module.
#!/usr/bin/env python | |
""" | |
This module could be used for benchmarking | |
ctypes. It is compared with math module. | |
""" | |
import ctypes | |
import sys | |
import math | |
import time | |
import random | |
def bench_ctypes(test_vector): | |
""" | |
CTypes testing function | |
""" | |
if sys.platform.startswith('linux'): | |
libm = ctypes.CDLL('libm.so') | |
else: | |
return | |
sin = getattr(libm, 'sin') | |
sin.argtypes = [ctypes.c_double] | |
sin.restype = ctypes.c_double | |
# Compute values | |
for val in test_vector: | |
sin(val) | |
def bench_math(test_vector): | |
""" | |
Math module testing unction | |
""" | |
# Compute values | |
for val in test_vector: | |
math.sin(val) | |
def gen_test_vector(num): | |
""" | |
This method generates vector with random numbers | |
""" | |
vector = [None] * num | |
while num > 0: | |
vector[num - 1] = random.random() | |
num -= 1 | |
return vector | |
def bench(num=1000000): | |
""" | |
This function benchmarks computation using | |
ctypes and math module | |
""" | |
test_vector = gen_test_vector(num) | |
start1 = time.time() | |
bench_ctypes(test_vector) | |
end1 = time.time() | |
print('ctypes:', end1 - start1) | |
start2 = time.time() | |
bench_math(test_vector) | |
end2 = time.time() | |
print('math:', end2 - start2) | |
if __name__ == '__main__': | |
bench() |
#!/usr/bin/env python | |
""" | |
This is simple example of using ctypes module | |
""" | |
import ctypes | |
import sys | |
def test_ctypes(): | |
""" | |
Main testing function | |
""" | |
if sys.platform.startswith('linux'): | |
libm = ctypes.CDLL('libm.so') | |
else: | |
return | |
sin = getattr(libm, 'sin') | |
sin.argtypes = [ctypes.c_double] | |
sin.restype = ctypes.c_double | |
val = sin(1.0) | |
print(val) | |
if __name__ == '__main__': | |
test_ctypes() | |
Current version works only at Linux, but it should be problem to port it for different platforms.