Real-world Python code 700 times slower than C
Skip Montanaro
skip at pobox.com
Sat Jan 5 13:53:38 EST 2002
Tim> By cheating a bit I came up with a version using Numeric that runs
Tim> more than 50x faster than the original Python version.
If Tim can cheat, so can I. ;-)
I modified the version I wrote that uses PyInline to use Py_List* macros to
set the elements of the array:
#!/usr/bin/env python
import PyInline
m = PyInline.build(code="""
void
Ramp(PyObject* result, int size, double start, double end)
{
double step = (end-start)/(size-1);
int i;
for (i = 0; i < size; i++) {
Py_DECREF(PyList_GET_ITEM(result, i));
PyList_SET_ITEM(result, i, PyFloat_FromDouble(start + step*i));
}
}
""", language="C")
def Ramp(result, size, start, end):
step = (end-start)/(size-1)
for i in xrange(size):
result[i] = start + step*i
def main(ramp):
array = [0.0]*10000
for i in xrange(100):
ramp(array, 10000, 0.0, 1.0)
import time
t1 = time.time()
main(m.Ramp)
t1 = time.time()-t1
print "fast:", t1
t2 = time.time()
main(Ramp)
t2 = time.time()-t2
print "slow:", t2
print "fast is", t2/t1, "times faster than slow"
This version runs about 17x faster than the pure Python version. (The first
version I posted ran about 7x faster.) I would have added a PyList_Check
test in there and done the usual set an exception and return NULL if the
test failed, but I don't couldn't (easily) figure out how PyInline handles
functions that return PyObject*.
--
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)
More information about the Python-list
mailing list