我有一個函式def act(obs)回傳一個浮點數并且計算量很大(需要一些時間來運行)。
import time
import random
def act(obs):
time.sleep(5) # mimic computation time
action = random.random()
return action
我經常在腳本中呼叫這個函式的速度比它執行的時間要快。呼叫該函式時我不希望有任何等待時間。相反,我更喜歡使用早期計算的回傳值。我如何實作這一目標?
我想到的是在函式中更新了一個全域變數,我一直在讀取全域變數,盡管我不確定這是否是實作它的最佳方法。
uj5u.com熱心網友回復:
這是我最終根據這個答案使用的
class MyClass:
def __init__(self):
self.is_updating = False
self.result = -1
def _act(self, obs):
self.is_updating = True
time.sleep(5)
self.result = obs
self.is_updating = False
def act(self, obs):
if not self.is_updating:
threading.Thread(target=self._act, args=[obs]).start()
return self.result
agent = MyClass()
i = 0
while True:
agent.act(obs=i)
time.sleep(2)
print(i, agent.result)
i = 1
uj5u.com熱心網友回復:
全域變數方式應該可以作業,你也可以有一個類,它有一個私有成員,比如result一個標志isComputing和一個方法getResult,compute()如果它當前沒有計算,它會呼叫一個方法(通過執行緒),并回傳以前的結果。該compute()方法應該isComputing正確更新標志。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/403385.html
標籤:
