I have a very long loop, and I would like to check the status every N iterations, in my specific case I have a loop of 10 million elements and I want to print a short report every millionth iteration.
So, currently I am doing just (n is the iteration counter):
if (n % 1000000==0): print('Progress report...')
but I am worried I am slowing down the process by computing the modulus at each iteration, as one iteration lasts just few milliseconds.
Is there a better way to do this? Or shouldn't I worry at all about the modulus operation?
To print something only every n iterations in python, a solution is to use a modulo operation (or operator % in python).
To count iterations we can use the Python enumerate() function and pass it in as the first argument of the for loop.
Iteration statements or loop statements allow us to execute a block of statements repeatedly as long as the condition is true. (Loops statements are used when we need to run same code again and again) Type of Iteration Statements In Python 3.
How about keeping a counter and resetting it to zero when you reach the wanted number? Adding and checking equality is faster than modulo.
printcounter = 0 # Whatever a while loop is in Python while (...): ... if (printcounter == 1000000): print('Progress report...') printcounter = 0 ... printcounter += 1
Although it's quite possible that the compiler is doing some sort of optimization like this for you already... but this may give you some peace of mind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With