[英]How do I get cpu_times of process run with psutil.Popen after it is finished but before it is terminated
我想使用psutil.Popen
對象的cpu_times()
方法來查找完成后的累積值。 我首先嘗試了以下方法:
p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
p.wait()
cpuTimes = p.cpu_times()
但是,這會導致NoSuchProcess
異常,因為wait()
在進程終止之前不會返回。 我接下來嘗試在調用cpu_times()
之前調用cpu_times()
wait()
:
p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
cpuTimes = p.cpu_times()
p.wait()
然而,這會產生全為零的響應。 我認為這是因為它在進程開始后立即被調用。 所以,我添加了一個對time.sleep()
的調用,它只會比這個過程更持久:
p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
time.sleep(15.) # b/c -t 15 in subprocess means it will take 15 seconds
cpuTimes = p.cpu_times()
p.wait()
這實際上產生了 45 秒的預期值(3 個 CPU 以 100% 的利用率持續 15 秒)。
但是,對於一般過程,我不知道需要多長時間才能完成。 我想避免添加任意大的睡眠時間,以確保在我進行查詢之前該過程已完成。
有沒有辦法在不調用wait()
或其他此類方法的情況下知道進程已完成,進程在其返回時已終止?
好的,我找到了解決方案。 這實際上非常簡單,所以我可能應該在發布我的問題之前考慮過它,但我想這些事情有時就是這樣。
p = psutil.Popen("stress --cpu 3 -v -t 15", shell=True)
cpuTimes = p.cpu_times()
while True:
time.sleep(1e-4)
cpuTimes = p.cpu_times() # Make sure to do this before the call to poll()
retCode = p.poll()
if retCode is not None:
break
在這里,我在啟動包含對cpu_times()
和poll()
方法的調用的子進程之后添加了一個循環。
poll()
方法是一種檢查子進程是否完成的非阻塞方式。 通過調用cpu_times()
調用前右poll()
時間微不足道的金額也就過去了,所以我們可以為所有意圖和目的,考慮到最后通話cpu_times()
以獲得准確的結果。
請注意,如果進程已完成,則在poll()
之后調用cpu_times()
時會出現異常。 這是另一個原因,將通話到cpu_times()
調用之前poll()
sleep()
方法的參數不是非常重要,但確實會影響子進程完成后和循環終止之前經過的時間。 如果子進程從未完成,您可能還可以添加某種慷慨的超時來防止無限循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.