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)?
We see that for creating same number of elements, for loop takes “14 seconds”, while list comprehension taks just about “9 seconds”. It is clear that for loop is much slower compared to list comprehension.
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)
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