all() is slow?

BOOK-AZ amalguseynov at gmail.com
Tue Nov 15 11:02:13 EST 2011


On Nov 7, 1:00 pm, "OKB (not okblacke)"
<brenNOSPAMb... at NObrenSPAMbarn.net> wrote:
>         I noticed this (Python 2.6.5 on Windows XP):
> http://book-az.com
> >>> import random, timeit
> >>> def myAll(x):
>
> ...     for a in x:
> ...         if a not in (True, False):
> ...             return False
> ...     return True>>> x = [random.choice([True, False]) for a in xrange(0, 5000000)]
> >>> timeit.timeit('myAll(x)', 'from __main__ import myAll, x',
>
> number=10)
> 0: 9.7685158309226452>>> timeit.timeit('all(a in (True, False) for a in x)', 'from __main__
>
> import x', number=10)
> 1: 12.348196768024984>>> x = [random.randint(0,100) for a in xrange(0, 5000000)]
> >>> def myAll(x):
>
> ...     for a in x:
> ...         if not a <= 100:
> ...             return False
> ...     return True>>> timeit.timeit('myAll(x)', 'from __main__ import myAll, x',
>
> number=10)
> 4: 2.8248207523582209>>> timeit.timeit('all(a <= 100 for a in x)', 'gc.enable(); from
>
> __main__ import x', number=10)
> 5: 4.6433557896324942
>
>         What is the point of the all() function being a builtin if it's
> slower than writing a function to do the check myself?
>
> --
> --OKB (not okblacke)
> Brendan Barnwell
> "Do not follow where the path may lead.  Go, instead, where there is
> no path, and leave a trail."
>         --author unknown




More information about the Python-list mailing list