0

I have to use a very long while loop in Python, so it takes quite a while for the program to finish executing. I would like to know, while the code is running, how long the program has left to complete.

I had thought of printing the number of the iteration in progress:

while N > 0:
    ...
    N = N-1
    print(N, "iterations completed")
            

However, I think this may be slowing down too much the execution. Is there maybe a better option?

Quaerendo
  • 107
  • 6

2 Answers2

2

use tqdm
an example :

from tqdm import tqdm

for n in tqdm(range(N)):
    ...
   #your code.

or
another library you can use progress bar

from progress.bar import Bar

bar = Bar('Processing', max=N)
for i in range(N):
    # Do some work
    bar.next()
bar.finish()
kiranr
  • 2,087
  • 14
  • 32
1

There is tqdm for this.

from tqdm import tqdm
for i in tqdm(range(N), desc='Iterations completed'):
    # do something
    pass
    
Alex Metsai
  • 1,837
  • 5
  • 12
  • 24
  • Can you show why this is better than using a simple `print`? – Tomerikoo May 06 '21 at 13:16
  • Yes, it's because printing spoils the outcome of `tqdm`'s output, meaning that it shows a newline in each iteration, instead of a single progress bar that the OP wants. – Alex Metsai May 06 '21 at 13:42
  • There are ways to overcome this using `print` (remember that behind the scenes `tqdm` simply prints...). The question asks for an efficient way. What makes this more efficient that a `print`? – Tomerikoo May 06 '21 at 13:46
  • Doesn't the fact that tqdm handles the printing gracefully suffy? Furthermore, the OP's code prints for every single iteration, considerably slowing down the loop. – Alex Metsai May 06 '21 at 15:08
  • I think that the above is the reason the OP considers his code inefficient. – Alex Metsai May 06 '21 at 15:09