[Python-Dev] heapq, min and max

Daniel Stutzbach daniel at stutzbachenterprises.com
Thu Oct 23 01:30:03 CEST 2008


On Wed, Oct 22, 2008 at 3:51 PM, Raymond Hettinger <python at rcn.com> wrote:

> Aside from list specialization versus a general iterator
> protocol, there is no fat in the min/max implementation.
> It loops, it compares, it returns.
>
> Also, a primary use case for min/max is with just two inputs.
> We don't want to slow that down in order to provide negligible
> improvements to min/max for long sequences.
>

If min/max were specialized for tuples, it would speed up the common case
where a handful of arguments are passed in.  Since tuples are immutable,
evil comparison functions can't permute the input, either.

I threw together a quick modification with tuple specialization, here are
the results:

2.6-pristine   2.6-patched
0.38usec       0.243usec      -36%     two integers
284usec       198usec          -30%    5000 integers
0.455usec     0.308usec      -32%     two datetime objects
600usec        536usec         -11%    5000 datetime objects

Not bad :-)

Raw commands and results are below:

Cashew:~/src-other/Python-2.6-pristine$ ./python.exe Lib/timeit.py
'max(2,8)'
1000000 loops, best of 3: 0.38 usec per loop

Cashew:/tmp/Python-2.6$ ./python.exe Lib/timeit.py 'max(2,8)'
1000000 loops, best of 3: 0.243 usec per loop

Cashew:~/src-other/Python-2.6-pristine$ ./python.exe Lib/timeit.py -s
'x=tuple(xrange(5000))' 'max(x)'
1000 loops, best of 3: 284 usec per loop

Cashew:/tmp/Python-2.6$ ./python.exe Lib/timeit.py -s
'x=tuple(xrange(5000))' 'max(x)'
10000 loops, best of 3: 198 usec per loop

Cashew:~/src-other/Python-2.6-pristine$ ./python.exe Lib/timeit.py -s
'import datetime' -s 'x = datetime.datetime.now()' -s 'y =
datetime.datetime.now()' 'max(x,y)'
1000000 loops, best of 3: 0.455 usec per loop

Cashew:/tmp/Python-2.6$ ./python.exe Lib/timeit.py -s 'import datetime' -s
'x = datetime.datetime.now()' -s 'y = datetime.datetime.now()' 'max(x,y)'
1000000 loops, best of 3: 0.308 usec per loop

Cashew:~/src-other/Python-2.6-pristine$ ./python.exe Lib/timeit.py -s
'import datetime' -s 'x = tuple(datetime.datetime.now() for x in
range(5000))' 'max(x)'
1000 loops, best of 3: 600 usec per loop

Cashew:/tmp/Python-2.6$ ./python.exe Lib/timeit.py -s 'import datetime' -s
'x = tuple(datetime.datetime.now() for x in range(5000))' 'max(x)'
1000 loops, best of 3: 536 usec per loop

(the one in /tmp/ is patched)

--
Daniel Stutzbach, Ph.D.
http://stutzbachenterprises.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20081022/56e71619/attachment.htm>


More information about the Python-Dev mailing list