I would like to be able to have a for loop execute different code depending on what 'mode' it is in, but in the name of efficiency not have to check this mode at every iteration. It's easy to do this if you allow these checks:
for i in range(n):
if m == 0:
# execute some code, test whether to update m
continue
if m == 1:
# execute some other code, test whether to update m
But what I would like is if the for loop kept its current mode and carried on unless it was specifically told to change it, to avoid the extra 'mode check' step on every iteration.
Weirdly, the only way I can think to do this is using goto statements, which I know can't be the answer!
i = 0
# start line for mode 1
# execute some code
i = 1
# test what mode to be in next, goto that line
# start line for mode 2
# execute some other code
i = 1
# test what mode to be in next, goto that line
# stop when you're at n
Hopefully you can see that these two theoretical programs achieve roughly the same thing, unless I've misunderstood somehow. However, the second one does not have to test its mode after every increment of i, because the action of testing what mode to be in next also puts it at the correct place to execute the right bit of code for that mode. The first one runs a test and updates m on one iteration, then has to test m on the next iteration to check what to do next.
I think that my theory is right and that a) these things are different and b) this should be possible (i.e. you don't need to do the 'double test'). If so, I would like some help implementing it in a neat way in python, please.
CodePudding user response:
You should start by asking if this is a meaningful optimization, or a pointless micro optimization. If your profiling reveals that a significant amount of time is being spent on checking the mode, you can avoid doing so with code roughly structured like this:
while True:
if m == 0:
while True:
# Do stuff here
# Run `break` when the mode changes
pass
elif m == 1:
while True:
# Do stuff here
# Run `break` when the mode changes
pass
The loops can be of any sort - whatever suits your needs. I would also recommend extracting the codeblocks under the if statements into functions that return instead of breaking:
def do_mode_0_stuff():
while True:
# Do stuff here
# Run `return` when the mode changes
pass
def do_mode_1_stuff():
while True:
# Do stuff here
# Run `return` when the mode changes
pass
while True:
if m == 0:
do_mode_0_stuff()
elif m == 1:
do_mode_1_stuff()
In the end I highly doubt this sort of restructuring will lead to any significant performance improvement, so I would go with whatever structure is most clear, elegant, and maintainable.