Newbie questions

Alex Martelli aleax at aleax.it
Tue Mar 25 00:06:34 CET 2003


Ladvánszky Károly wrote:

> I've forgotten to mention some details that might be interesting.
> To create 500000 objects, both versions run cca. 17 secs on a 600MHz PC.

With Python 2.3, a suitably designed TestClass, and an old Athlon 1.2 GHz,
we can do quite a bit better in various ways -- here's an example of how
to use timeit from within your programs:

import timeit

mk_tc = """
class TestClass(object):
        __slots__ = ['j',]
        def __init__(self, j): self.j = j
cnt = 500*1000
"""

with_map = "ls = map(TestClass, xrange(cnt))"

with_lc = "ls = [TestClass(j) for j in xrange(cnt)]"

with_loop = """ls = cnt*[None]
for j in xrange(cnt):
        ls[j] = TestClass(j)
"""

for name, statement in zip('map lc loop'.split(),
                           [with_map, with_lc, with_loop]):
    tim = timeit.Timer(statement, setup=mk_tc).timeit(1)
    print "%4s %s" % (name, tim)


This tells me:

[alex at lancelot alex]$ python totim.py
 map 2.26362597942
  lc 2.48765206337
loop 2.71629798412
[alex at lancelot alex]$

I'm a bit surprised that the list comprehension is faster
now, but this IS quite repeatable on this box &c:

[alex at lancelot alex]$ python totim.py
 map 2.29507398605
  lc 2.48321902752
loop 2.67293393612
[alex at lancelot alex]$


Alex





More information about the Python-list mailing list