1
我目前正在研究一個程序,該程序將顯示自特定點以來經過的時間量。一個秒錶,如果你願意。時間不準確或低效代碼?
我終於得到了我的代碼工作,但事實證明,這不是很準確。它很快就落後了,在跑步的前10秒內就是1秒甚至2秒,我不完全確定這是爲什麼。
# Draw
def draw():
stdscr.erase()
stdscr.border()
# Debugging
if debug:
stdscr.addstr(5 , 3, "running : %s " % running)
stdscr.addstr(6 , 3, "new : %s " % new)
stdscr.addstr(7 , 3, "pureNew : %s " % pureNew)
stdscr.addstr(8 , 3, "paused : %s " % paused)
stdscr.addstr(9 , 3, "complete : %s " % complete)
stdscr.addstr(10, 3, "debug : %s " % debug)
if running:
stdscr.addstr(1, 1, ">", curses.color_pair(8))
stdscr.addstr(1, 3, t.strftime("%H:%M.%S", t.gmtime(timeElapsedTotal)))
elif not running:
if new and pureNew:
stdscr.addstr(1, 1, ">", curses.color_pair(5))
stdscr.addstr(1, 3, t.strftime("%H:%M.%S", timeNone))
elif paused:
stdscr.addstr(1, 3, t.strftime("%H:%M.%S", t.gmtime(timeElapsedTotal)), curses.color_pair(1))
stdscr.addstr(1, 1, ">", curses.color_pair(3))
else:
stdscr.addstr(1, 1, ">", curses.color_pair(5))
stdscr.addstr(1, 3, t.strftime("%H:%M.%S", timeNone))
stdscr.redrawwin()
stdscr.refresh()
return
# Calculations
def calc():
global timeElapsedTotal
if running:
timeElapsedTotal = t.clock() - timeStart
return
# Main Loop
while True:
# Get input from the user
kInput = stdscr.getch()
# If q is pressed we close the program
if kInput == ord('q'):
endProg()
# If d is pressed we toggle 'debug' mode
elif kInput == ord('d'):
debug = not debug
# If s is pressed we stop the current run
elif kInput == ord('s'):
running = False
new = True
# If spacebar is pressed and we are ready for a new run,
# we start a new run
elif kInput == ord(' ') and new:
running = not running
new = not new
pureNew = False
timeStart = t.clock()
# If p is pressed and we are in the middle of a run,
# we pause the run
elif kInput == ord('p') and not new:
running = not running
paused = not paused
timeStart = t.clock() - timeStart
calc()
draw()
就我所知,上述代碼是按照預期工作的。我不確定延遲是否來自time.clock()
或者它只是我低效的代碼。這是我需要使用線程進行的工作嗎?
我做了一些Google搜索,看到其他人在討論時間模塊中的其他功能,但沒有一個對我更好。
讓我知道,如果這是不夠的信息或我犯了一個簡單的錯誤。
'time.clock'在不同的操作系統上意味着不同的東西 - 非常煩人,但它就是這樣。在Linux上它的執行時間已經過去了,而不是掛鐘時間,不應該用來計算秒數。 – tdelaney
@tdelaney好吧,這是有道理的。你知道任何好的選擇嗎?我會使用datetime模塊遇到同樣的問題,還是下一步呢? – Ophi
我不知道是否有一個更現代的方法來解決這個問題,但在當天我會檢查我是否在Linux上運行(高分辨率牆上時鐘是time.time())或windows(高分辨率牆上時鐘是time.clock)通過'platform.system()'並從那裏選擇一個時鐘。 – tdelaney