On Fri, 20 Oct 2006 02:16:30 -0700, Joshua Kantor <[EMAIL PROTECTED]> wrote:
> The example I send I had modified before sending it and > apparently in that example the Py_INCREF I had isn't necessary, > I've attached the original example I had where it is necessary. > Consider foo vs foo_bar. foo works once but crashes if you run it again > on > the same tuple or try and do anything with that tuple foo_bar works fine > repeatedly no crashes. > This is a very good sign that you're doing something right: sage: time foo_bar(range(10^6)) CPU times: user 0.29 s, sys: 0.01 s, total: 0.29 s Wall time: 0.30 499999500000L sage: time sum(range(10^6)) CPU times: user 0.31 s, sys: 0.01 s, total: 0.31 s Wall time: 0.32 499999500000L I tried another function I just saw in the Python/C API, and I'm able to *beat* the built-in sum function. Cool! sage: time mysum(range(10^6)) CPU times: user 0.29 s, sys: 0.01 s, total: 0.29 s Wall time: 0.30 499999500000L sage: time sum(range(10^6)) CPU times: user 0.31 s, sys: 0.01 s, total: 0.32 s Here's how mysum is defined in Pyrex. Note the trick of void pointers to avoid Pyrex reference counting, etc: cdef extern from "Python.h": object PySequence_Fast(object,char *) int PySequence_Size(object) object PySequence_Fast_GET_ITEM(object, int) void** PySequence_Fast_ITEMS(object o) void Py_INCREF(object) def mysum(x): cdef object seq cdef int len,i cdef object item cdef object total total = 0 seq = PySequence_Fast(x,"Expected sequence") len = PySequence_Size(x) cdef void** X X = PySequence_Fast_ITEMS(seq) for i from 0 <=i<len: item = <object>X[i] total = total + item return (total) So, maybe this is the best way to iterate through a Python list. William --~--~---------~--~----~------------~-------~--~----~ To post to this group, send email to sage-devel@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/sage-devel URLs: http://sage.scipy.org/sage/ and http://modular.math.washington.edu/sage/ -~----------~----~----~----~------~----~------~--~---