ctypes speed question

I’ve been trying to figure out how to speed up python code using ctypes and I’m a little confused by what I’m finding.

first I just tried this -


from ctypes import *
y = 10000
#COMPARING RUNTIME OF THIS LOOP
for x in range(y): 2 * 2 
a = c_int(2)
#TO THIS LOOP
for x in range(y): a.value * a.value

I realized that in this the ctypes is slower b/c I think it has to convert back to a
python type for the operation or something to that effect.

so I found some more info on creating dll’s and was able to get one loaded.

—test.c—


#include <stdio.h>
void _init()
{
    printf("Init
");
}
void _fini()
{
    printf("Clean-up
");
}
int mult(int a, int b)
{
    return(a*b);
}

compiled to a dll, then…

—test.py—


from ctypes import *
lib = cdll.LoadLibrary("C:\\mycpp\	est.dll")
print(lib.mult(6,9))

y = 10000
tt0 = time.clock()

for a in range(y): a * a
tt1 = time.clock()

for a in range(y): lib.mult(a,a)
tt2 = time.clock()

print('pyTime: ', tt1-tt0)
print('ctTime: ', tt2-tt1)

unfortunately I found this is still much slower than multiplying in python, about 8x slower.

So am I doing something horribly wrong here? Any help would be very appreciated. Thanks.

teldredge