Python loop time

I am trying to loop a while loop in a while loop, the total time it takes to execute, and write down the time it takes to do this, every time it loops. I need a way to achieve this using my code, if possible, or open up various concepts that I don't know about 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 the time, but I am very sure that it does not take into account the wait time of the nested loop. How can I let python use the time both in the loop and in each loop that it will need to do (in this case 500)?

+5
source share
3 answers

, , , while. :

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

, , . , , .

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)
+10

, - , :

import random
import time import sys

def main():

    looperCPU = 500
    start = time.time()
    while (looperCPU != 0):
       #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
       myStart = time.time()
       while printerLooper == True :
          print("Sleeping for ", secondsPause, " seconds")
          print(random_number)
          printerLooper = False
          print("total time taken this loop: ", time.time() - myStart)    

       looperCPU -= 1    
main()
+1

In python, you can study this document https://docs.python.org/2/library/timeit.html
Stackoverflow example: How to use the timeit module

import timeit
timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)

In a Jupyter Laptop

%%timeit -n 100
import pandas as pd
s = pd.Series([101.00, 121.00])
summary = 0
for item in s:
    summary+=item
+1
source

All Articles