Optimizing constants in loops

M

Michael Hoffman

The peephole optimizer now takes things like

if 0:
do_stuff()

and optimizes them away, and optimizes away the conditional in "if 1:".

What if I had a function like this?

def func(debug=False):
for index in xrange(1000000):
if debug:
print index
do_stuff(index)

Could the "if debug" be optimized away on function invocation if debug
is immutable and never reassigned in the function? When performance
really matters in some inner loop, I usually move the conditional
outside like this:

def func(debug=False):
if debug:
for index in xrange(1000000):
print index
do_stuff(index)
else:
for index in xrange(1000000):
do_stuff(index)

It would be nice if this sort of thing could be done automatically,
either by the interpreter or a function decorator.
 
T

Thomas Heller

Michael said:
The peephole optimizer now takes things like

if 0:
do_stuff()

and optimizes them away, and optimizes away the conditional in "if 1:".

What if I had a function like this?

def func(debug=False):
for index in xrange(1000000):
if debug:
print index
do_stuff(index)

Could the "if debug" be optimized away on function invocation if debug
is immutable and never reassigned in the function? When performance
really matters in some inner loop, I usually move the conditional
outside like this:

def func(debug=False):
if debug:
for index in xrange(1000000):
print index
do_stuff(index)
else:
for index in xrange(1000000):
do_stuff(index)

It would be nice if this sort of thing could be done automatically,
either by the interpreter or a function decorator.

Just use the builtin __debug__ variable for that purpose.
__debug__ is 'True' if Python is run normally, and 'False'
if run with the '-O' or '-OO' command line flag.
The optimizer works in the way you describe above (which
it will not if you use a custom variable).

Thomas
 
M

Michael Hoffman

Thomas said:
Just use the builtin __debug__ variable for that purpose.
__debug__ is 'True' if Python is run normally, and 'False'
if run with the '-O' or '-OO' command line flag.
The optimizer works in the way you describe above (which
it will not if you use a custom variable).

Thanks, I didn't know that __debug__ was optimized like this. But that
was really just a specific example of the general case.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top