2013-02-07 18 views
5

私はwhileループ内でwhileループを実行しようとしています。実行するのにかかる合計時間と、ループするたびにその時間を記録します。可能であれば、私のコードを使ってこれを達成する方法が必要です。あるいは、私がまだ分かっていないかもしれないさまざまな概念を開くことができます。whileループ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ループの睡眠時間を取っていない非常に確信しています。どのようにしてPythonが両方のループを実行できるようにすることができますか(この場合は500)、すべてのループを実行する必要がありますか?

+0

http://stackoverflow.com/questions/1557571/python-program-execution-time-of-a-get-to-get-time-of-a-pythonプログラムの実行。 – 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)) 

あなたの終了時刻が着実に時間の経過とともに増加している間、スタートが全体の実行時間の静的とどまるためです:それは言ってようなものです。 ループ内に開始時間を配置することで、プログラムの実行に伴い開始時間も増加することを確認します。 Pythonで

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