Packing data

Erno Kuusela erno-news at erno.iki.fi
Thu May 2 12:13:52 EDT 2002


In article <MPG.173a32a9eb02be4a9896d0 at news.nwlink.com>, Jeff Shannon
<jeff at ccvcorp.com> writes:

| Presuming that var is a list of ints, the following will be much 
| more efficient than your code, without requiring array/struct.

| def mkstring(var):
|     var = [chr(a) for a in var]
|     return ''.join(var)

import string, time

def time_fun(f):
    start = time.time()
    f()
    elapsed = time.time() - start
    print f, round(elapsed, 2)

L = [42]*1000000

def listcomp_test():
    return string.join([chr(x) for x in L], '')

def map_test():
    return string.join(map(chr, L), '')

assert map_test() == listcomp_test()
for f in listcomp_test, map_test:
    time_fun(f)


prints, for me:

% python ding.py
<function listcomp_test at 1482a4> 6.82
<function map_test at 1482d4> 1.83
python ding.py  17.44s user 0.16s system 98% cpu 17.897 total

the map version is also more readable, imho.

  -- erno



More information about the Python-list mailing list