我正在開發一個 Tkinter python 游戲——長話短說它需要能夠以不同的 FPS 值運行。但是,我無法保持一致的第二長度。
我試圖讓它檢測滯后并將其從 .after() 函式中移除:
def UpdatesEveryFrame():
s = time.perf_counter()
# Code here
s = int((time.perf_counter() - s)*1000)
LabelProductionTime3.after(int(1000 / fps) - s, UpdatesEveryFrame)
然而,這是不成功的。它似乎以毫秒(通常在 15 左右)為單位創建了一個準確的值,但這并不能產生準確的秒延遲。我嘗試過替換perf_counter(),time()但這具有相同的效果。
由于游戲的基礎,有一個準確的第二延遲是必不可少的。你能幫我嗎?謝謝。
uj5u.com熱心網友回復:
如果這里的目標是精度,那么也許你應該嘗試time.perf_counter_nstime 模塊的方法,它具體地比 更精確time.perf_counter,并且以納秒為單位給出時間,如果必須將時間轉換回秒,它可以是使用單位轉換完成。
此外, time.perf_counter 方法的檔案也提到了這一點 - :
使用 perf_counter_ns() 可以避免浮點型別導致的精度損失。
def UpdatesEveryFrame():
s = time.perf_counter_ns()/(10 ** 9) # used perf_counter_ns, divided by (10 ** 9) to convert to seconds.
# Code here
s = int((time.perf_counter_ns()/(10 ** 9) - s)*1000) # used perf_counter_ns, divided by (10 ** 9) to convert to seconds.
LabelProductionTime3.after(int(1000 / fps) - s, UpdatesEveryFrame)
編輯:
還有time.monotonic一種方法,專門設計用于測量兩次連續呼叫之間經過的時間,它以類似于 的小數秒為單位回傳時間time.perf_counter,因此除了函式本身的名稱外,無需在當前代碼中進行任何更改。
def UpdatesEveryFrame():
s = time.monotonic() # Changed method name.
# Code here
s = int((time.monotonic() - s)*1000)
LabelProductionTime3.after(int(1000 / fps) - s, UpdatesEveryFrame) # Changed method name.
此外,與time.perf_counter_ns作為 的更精確版本可用的方法類似time.perf_counter,也存在time.monotonic以納秒為單位回傳時間和功能類似于 的更精確版本的方法time.monotonic,即time.monotonic_ns.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/431682.html
