How can I speed this function up?

nnorwitz at gmail.com nnorwitz at gmail.com
Sat Nov 18 17:46:26 EST 2006


Peter Otten wrote:
>
> # Norvitz/Lundh
> def writelines_data(out, data, map=map, str=str):
>       SPACE_JOIN = ' '.join
>       out.writelines(
>          "ELEMENT %06d %s\n" % (i1, SPACE_JOIN(map(str, i2)))
>                for i0, i1, i2 in data if i0 == 'ELEMENT'
>          )
>
> def print_data(out, data):
>     for name, index, items in data:
>         if name == "ELEMENT":
>             print >> out, "ELEMENT %06d" % index,
>             for item in items:
>                 print >> out, item,
>             print >> out
>
> Output on my machine:
>
> $ python2.5 writedata.py
> write_data 10.3382301331
> writelines_data 5.4960360527
> print_data 3.50765490532

Interesting.  I timed with python2.4 and get this:

write_data 12.3158090115
writelines_data 5.02135300636
print_data 5.01881980896

A second run yielded:

write_data 11.5980260372
writelines_data 4.8575668335
print_data 4.84622001648

I'm surprised by your numbers a bit because I would expect string ops
to be faster in 2.5 than in 2.4 thanks to /F.  I don't remember other
changes that would cause such an improvement for print between 2.4 and
2.5.  (2.3 shows print doing a bit better than the times above.)

It could be that the variability is high due to lots of I/O or even
different builds.  I'm on Linux.

> Moral: don't forget about good old print. It does have an opcode(*) of its
> own, after all.

Using print really should be faster as less objects are created.

> (*) or two

or 5 :-)

$ grep 'case PRINT_' Python/ceval.c
                case PRINT_EXPR:
                case PRINT_ITEM_TO:
                case PRINT_ITEM:
                case PRINT_NEWLINE_TO:
                case PRINT_NEWLINE:

n




More information about the Python-list mailing list