2013-02-07 6 views
5

while 루프 내에서 while 루프를 실행하려고 할 때마다 실행하는 데 걸리는 총 시간과 반복 할 때마다 걸리는 시간을 기록하려고합니다. 가능한 경우 내 코드를 사용하여이 작업을 수행 할 수있는 방법이 필요하며 아직 모르는 다른 개념을 열어 두어야합니다.while while while loop python

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() 

루프에 시간이 인쇄되지만 중첩 된 while 루프 시간을 고려하지 않은 것이 확실합니다. 파이썬이 두 while 루프,이 루프에서해야 할 모든 루프 (이 경우 500)를 모두 시간을 허용하도록하려면 어떻게해야합니까?

+0

http://stackoverflow.com/questions/1557571/python-program-execution-time-of-get-time-of-time을 제공합니다. – Greg

+0

@greg 내 코드를 읽으면 그 타이밍 모듈을하고있다. 내가 알아 내려고하는 것은 전체 프로그램의 기본 타이밍보다 더 깊습니다. 모든 루프에 대해 시간을 측정해야합니다. – Bain

+0

베인, 내 실수. – Greg

답변

10

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

굉장히 필요한 부분입니다. 어떻게 든 나는 나의 시간 배치를 엉망으로 만들었다. 이 개념을 가져 주셔서 감사합니다. – Bain

1

오른쪽 생각은하지만, 타이밍 기능의 당신의 위치가 조금이라도 오프, 내가 여기를 수정 한 것입니다 : 당신은 당신이를지고 있음을 보장하는 초기 루프 밖에서 시작 설정

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()