2013-10-17 17 views
0
import time 

number = 1 
while number > 0: 
    print "Testing" 
    time.sleep(5) #print every 5 seconds 

這只是一個示例循環。我是一名半初學者,我不確定如何進行按鍵(任何按鍵都可以)顯示程序運行的時間。該程序將在Windows 7和Linux上運行。我如何做一個按鍵顯示我的程序運行了多久?

非常感謝。

回答

2

歡迎來到Stack Overflow和Python!你會喜歡它的。

首先,我會告訴你如何打印出你的代碼已經運行的時間。 time模塊包含一個time()函數,它將當前時間作爲Unix時間戳(自1970年1月1日以來的秒數)。如果您在函數的開始處將它分配給一個變量,您可以簡單地在循環中調用它,並從當前時間中減去它以獲得運行時間。和我一起到目前爲止?

(您也可以刪除您number變量和number > 0檢查,只需用True取代它。)

import time 

start_time = time.time() 
while True: 
    print "I've been running for %d seconds!" % (time.time() - start_time) 
    time.sleep(5) #print every 5 seconds 

但你問怎麼給每個用戶按下一個鍵時得到它。如果你只是想「進」,你可以這樣做:

import time 

start_time = time.time() 
while True: 
    print "I've been running for %d seconds!" % (time.time() - start_time) 
    raw_input("Press Enter...") 

raw_input()功能會等待用戶按Enter鍵,然後打印出的運行時間。

+0

我不知道這是可能的,但如果我按下Enter鍵,它說:「我一直在運行5秒鐘」,然後我機10秒後進入, python可以刪除初始輸出並將其更改爲15秒。 (試圖避免滾動時間輸出) – user1539175

+0

@ user1539175,看看http://stackoverflow.com/questions/6169217/replace-console-output-in-python –

+0

@BiRico問題是,鑑於上面的例子使用'raw_input',你使用Enter鍵來獲得下一行。如果你想避免這種情況,實際的答案會變得更加複雜。 –

0

一次一個問題。

  1. 你怎麼找到你的程序在你想要計算的點上運行了多長時間?
  2. 如何檢測按鍵?
  3. 如何讓程序產生1)2)何時發生?

依次嘗試每個問題,然後詢問您是否需要幫助。

0

這樣一個簡單的問題有很多複雜性和方法。

如果您正在查找當前正在運行的進程的正常運行時間,請使用OS通過子進程模塊查詢該進程以運行命令行操作,如'ps | grep「foo」'

通常,程序一次只能做一件事。例如,代碼可以工作或尋找按鍵。如果您需要運行必須同時運行兩個不同的代碼段,則將代碼段生成(運行)爲單獨的線程。對於你的問題,你可以產生兩個線程(代碼片斷),一個工作和一個查詢時間。

使用python中的線程模塊來封裝worker函數並創建一個查詢線程。但是,當工作線程完成時,您還需要查詢線程也終止。一種方法是將其定義爲守護進程線程。守護程序線程在它們是唯一活動的線程時終止。

例如:

from time import sleep 
import datetime 
import threading 


def do_someting(): 
    MAX_RUN_TIME = 300 #Seconds 
    for i in xrange(MAX_RUN_TIME): 
     print i, 
     sleep (1) 


class worker_thread(threading.Thread): 

    def run(self): 
     do_someting() 


class keypress_daemon_thread(threading.Thread): 

    def __init__(self): 
     threading.Thread.__init__(self) # Initialize the parent class 
     self.daemon = True # Terminates if only daemon threads are left 

    def run(self): 
     startTime = datetime.datetime.now() 
     while True: 
      raw_input() 
      timeDelta = datetime.datetime.now() - startTime 
      print 'Up for', timeDelta 


if __name__ == '__main__': 
    workerThread = worker_thread() 
    keyPressThread = keypress_daemon_thread() 
    workerThread.start() 
    keyPressThread.start() 
    workerThread.join() 
相關問題