Optimizing multiple dispatch

Jeff Epler jepler at unpythonic.net
Thu Jun 3 09:54:49 EDT 2004


Avoding map() may help:
    tuple([type(a) for a in args])
Using generator expressions (aren't they in 2.4?) might or might not
help:
    tuple(type(a) for a in args)

You could write a small extension to perform this operation without all
the Python function calls.

cdef extern from "Python.h":
    extern int PyTuple_Check(object)
    extern object PyTuple_New(int)
    extern int PyTuple_GET_SIZE(object)
    extern void *PyObject_Type(void*)
    extern void PyTuple_SET_ITEM(object, int, void*)
    extern void *PyTuple_GET_ITEM(object, int)

def maptype(i):
    if not PyTuple_Check(i): raise TypeError
    cdef int l 
    cdef int j
    l = PyTuple_GET_SIZE(i)
    o = PyTuple_New(l)
    for j from 0 <= j < l:
        PyTuple_SET_ITEM(o, j, PyObject_Type(PyTuple_GET_ITEM(i, j)))
    return o

>>> print maptype.maptype(("", 0, 0.0, 0L, str, int, type))
(<type 'str'>, <type 'int'>, <type 'float'>, <type 'long'>, <type 'type'>, <type 'type'>, <type 'type'>)

$ timeit -s 's = ("", 0, 0.0, 0L, str, int, type); from maptype import maptype' 'maptype(s)'
100000 loops, best of 3: 2.41 usec per loop
$ timeit -s 's = ("", 0, 0.0, 0L, str, int, type)' -s 'def maptype(s): return tuple([type(i) for i in s])' 'maptype(s)'
10000 loops, best of 3: 25.3 usec per loop
$ timeit -s 's = ("", 0, 0.0, 0L, str, int, type)' -s 'def maptype(s): return tuple(map(type, s))' 'maptype(s)'
100000 loops, best of 3: 17 usec per loop

... hmm, map is faster than listcomp.  my mistake!

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040603/32e6f8a1/attachment.sig>


More information about the Python-list mailing list