Which happens first?

Steve Holden sholden at holdenweb.com
Sun Apr 8 18:00:11 EDT 2001


"Carlos Alberto Reis Ribeiro" <cribeiro at mail.inet.com.br> wrote ...
[...discussion of optimizations...]
>
> For expressions that gets executed only once, you're right, there's no big
> deal. However, sometimes the expression gets calculated in the middle of a
> loop. It will have a impact on the overall speed. And worse, it may be
hard
> to discover why, even after running the profiler.
>
> Let us say that we have such a loop, using a high speed construction such
> as map. For instance,
>
> HEIGHT = 10
> WIDTH  = 10
> DEPTH  = 10
> z = map (lambda x: x * (HEIGHT * WIDTH * DEPTH), a)
>
> At first, you could think that there is nothing in this expression to
> optimize it. However, the expression above is about 68% slower than the
> direct calculation:
>
> z = map (lambda x: x * 1000, a)
>
I have seen documentation on improving Python execution speed (no, of course
I can't remember *where*), which points out the need to move constant
calculations out of loops.

With modern compiler technology it might be easy to assume that constant
folding would make your two expressions equivalent, but I remember Tim
Peters writing some time in the last year that no such feature was included
in the 2.0 interpreter. Plus, of course, technically your first expression
does not use constants, and so optimization would rely on complex flow
analysis which nobody is about to program for Python.

I believe there may be a case for compile-time folding of literal constants,
to ensure that 10*10 was actually treated as 100, that "#"*30 was treated as
"##############################" and so on. But this probably would not
yield too much in the way of performance gain.

AS already suggested in this thread, of course the best action before (as
Tim would so elegantly say) optimizing the snot out of your program would be
to get it working and profile it. Then you have data which will allow you to
maximize the return on your efforts. Which, by the way, I am not trying to
belittle. I agree that Python *should* generate better code, and your
analysis may help.

just-don't-see-myself-writing-the-PEPs-or-modifying-the-compiler-ly y'rs  -
steve








More information about the Python-list mailing list