Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute statement every N iterations in Python

Tags:

python

loops

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?

like image 501
Andrea Zonca Avatar asked Apr 11 '11 22:04

Andrea Zonca


People also ask

How do I print all iterations in Python?

To print something only every n iterations in python, a solution is to use a modulo operation (or operator % in python).

How do I find the number of iterations in Python?

To count iterations we can use the Python enumerate() function and pass it in as the first argument of the for loop.

What are iteration statements in Python?

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.


1 Answers

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.

like image 135
AndrewKS Avatar answered Nov 09 '22 06:11

AndrewKS