Bain Bain - 1 month ago 6
Python Question

Time a while loop python

I'm trying to time a while loop within a while loop, total time it takes to execute, and record the time it takes to do so, every time it loops. I need a way to achieve this using my code if possible, or open to different concepts I may not know of yet.

import random
import time
import sys

def main():


looperCPU = 500
start = time.time()
while (looperCPU != 0):
#start = time.time()

#this is the computation for 3 secs
time.sleep(3)
random_number = random.randint(0,1000)

#Send to printer for processing
#.75 secs to 4.75 secs to generate a pause before printing
secondsPause = random.uniform(.75,4.75)


#This is the printer function
printerLooper = True
while printerLooper == True :
print("Sleeping for ", secondsPause, " seconds")
print(random_number)
printerLooper = False


#
print("total time taken this loop: ", time.time() - start)
looperCPU -= 1



main()


The loop will print a time, but I'm very certain it is not taking into account the nested while loop sleep time. How can I allow python to time both while loops, every loop that it will need to do (in this case 500)?

Answer

When you set start outside your initial loop you are guaranteeing that you are getting the incorrect time it takes for the while loop to execute. It would be like saying:

program_starts = time.time()
while(True):
    now = time.time()
    print("It has been {0} seconds since the loop started".format(now - program_starts))

This is because start stays static for the entire execution time while your end time is steadily increasing with the passing of time. By placing start time within the loop you ensure that your start time is also increasing as the program runs.

while (looperCPU != 0):
    start_time = time.time()
    # Do some stuff
    while printerLooper == True :
        print("Sleeping for ", secondsPause, " seconds")
        print(random_number)
        printerLooper = False
    end_time = time.time()

    print("total time taken this loop: ", end_time - start_time)
Comments