Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Track and display percentage of code already executed

Tags:

python

I have a very large code that takes some time to run. In order to make sure the process hasn't stalled somewhere I print to screen the percentage of the code that has already been executed, which depends on a for loop and an integer.

To display the percentage of the for loop already processed I use flags to indicate how much of the loop already passed.

The MWE might make it a bit more clear:

import time

N = 100

flag_15, flag_30, flag_45, flag_60, flag_75, flag_90 = False, False,\
False, False, False, False

for i in range(N):

    # Large block of code.
    time.sleep(0.1)

    if i + 1 >= 0.15 * N and flag_15 is False:
        print '15%'
        flag_15 = True
    elif i + 1 >= 0.3 * N and flag_30 is False:
        print '30%'
        flag_30 = True
    elif i + 1 >= 0.45 * N and flag_45 is False:
        print '45%'
        flag_45 = True
    elif i + 1 >= 0.6 * N and flag_60 is False:
        print '60%'
        flag_60 = True
    elif i + 1 >= 0.75 * N and flag_75 is False:
        print '75%'
        flag_75 = True
    elif i + 1 >= 0.9 * N and flag_90 is False:
        print '90%'
        flag_90 = True
    elif i + 1 == N:
        print '100%'

This works but is quite verbose and truly ugly. I was wondering if there might be a better/prettier way of doing this.

like image 706
Gabriel Avatar asked Mar 21 '23 07:03

Gabriel


1 Answers

I like to use modulus to periodically print status messages.

import time

N = 100
for i in range(N):
    #do work here
    if i % 15 == 0:
        print "{}% complete".format(int(100 * i / N))
print "100% complete"

Result:

0% complete
15% complete
30% complete
45% complete
60% complete
75% complete
90% complete
100% complete

for values of N other than 100, if you want to print every 15%, you'll have to dynamically calculate the stride instead of just using the literal 15 value.

import time
import math

N = 300
percentage_step = 15
stride = N * percentage_step / 100 
for i in range(N):
    #do work
    if i % stride == 0:
        print "{}% complete".format(int(100 * i / N))
like image 130
Kevin Avatar answered Apr 01 '23 22:04

Kevin