count

J. Clifford Dyer jcd at sdf.lonestar.org
Thu Jul 9 04:10:47 CEST 2009


On Wed, 2009-07-08 at 14:45 -0700, Paul Rubin wrote:
> aahz at pythoncraft.com (Aahz) writes:
> > >Avoid that len(tuple(g)), use something like the following, it's lazy
> > >and saves some memory.
> > The question is whether it saves time, have you tested it?
> 
> len(tuple(xrange(100000000))) ... hmm.

timer.py
--------
from datetime import datetime

def tupler(n):
    return len(tuple(xrange(n)))

def summer(n):
    return sum(1 for x in xrange(n))

def test_func(f, n):
    print f.__name__,
    start = datetime.now()
    print f(n)
    end = datetime.now()
    print "Start: %s" % start
    print "End: %s" % end
    print "Duration: %s" % (end - start,)

if __name__ == '__main__':
    test_func(summer, 10000000)
    test_func(tupler, 10000000)
    test_func(summer, 100000000)
    test_func(tupler, 100000000)

$ python timer.py
summer 10000000
Start: 2009-07-08 22:02:13.216689
End: 2009-07-08 22:02:15.855931
Duration: 0:00:02.639242
tupler 10000000
Start: 2009-07-08 22:02:15.856122
End: 2009-07-08 22:02:16.743153
Duration: 0:00:00.887031
summer 100000000
Start: 2009-07-08 22:02:16.743863
End: 2009-07-08 22:02:49.372756
Duration: 0:00:32.628893
Killed
$ 

Note that "Killed" did not come from anything I did.  The tupler just
bombed out when the tuple got too big for it to handle.  Tupler was
faster for as large an input as it could handle, as well as for small
inputs (test not shown).




More information about the Python-list mailing list