Creating variables on the fly...
Emile van Sebille
emile at fenx.com
Fri Apr 7 10:35:20 EDT 2000
Lately, I've become skeptical of faster claims
when they point away from the obvious. I know
that there are exceptions, but this is not one.
For a small number of arguments, the difference
is negligible but measurable at a high number of
iterations. The gap widens with more arguments.
Emile van Sebille
emile at fenx.com
--------------------
from time import time
def add1(*args):
sum=0
for arg in args:
sum=sum+arg
return sum
def add2(*args):
return reduce(lambda x, y: x+y, args)
items = (107, 132, 147, 159, 183,
194, 204, 285, 294, 1107,
2132, 3147, 4159, 5183, 6194,
7204, 8285, 9294, 10483, 14572)
for count in (3, 8, 14, 20):
print '\n---%s---' % count
for iterations in (5000, 15000, 50000):
print " ", iterations,":\n",
for func in (add1, add2):
print ' ',func.__name__,
start = time()
for i in range(iterations):
apply(func, items[:count])
print '%6.2f' % (time()-start)
-------------------
----- Original Message -----
From: Tomek Lisowski <Lisowski.Tomasz at sssa.nospam.pl>
Newsgroups: comp.lang.python
To: <python-list at python.org>
Sent: Thursday, April 06, 2000 9:23 PM
Subject: Odp: Creating variables on the fly...
> U¿ytkownik Joachim Kaeber <kaeber at gmd.de> w wiadomooci do grup
dyskusyjnych
> napisa³:38E8EFF0.D71D0415 at gmd.de...
> > Hi,
> >
> > what about this:
> >
> > def add(*args):
> > sum=0
> > for arg in args:
> > sum=sum+arg
> > return sum
> >
> > add(1,2,3,4)
> > => 10
> >
> > add (1,2,3,4,5,6,7)
> > => 28
>
> Why not:
>
> def add(*args):
> return reduce(lambda x, y: x+y, args)
>
> I am not completely sure, but it may be faster, than a Python for loop
>
> Tomasz Lisowski
>
More information about the Python-list
mailing list