我正在嘗試測量 Python 程式的執行時間。為此,我正在使用該perf_counter()庫。
我的問題不在于圖書館,而在于如何衡量具體案例。
問題是我的程式包含一個while,我特別想知道while的條件消耗了多少執行時間(對于那些感興趣的人:這是因為while的條件是一個很長的邏輯公式是可以滿足的,所以這個衛星搜索可能很昂貴)。
我的問題是,我該如何計算這個?
我的意思是,我可以(如下所示)重新執行條件并保存它,但這對我來說不是解決方案,因為(1)時間可能與執行 while 條件的時間不同,并且,以上全部,(2)最好不要重新執行代碼,因為這會偽造總執行的實時時間。
t_start = perf_counter()
...
t_condition = 0
while condition:
t_conditionStart = perf_counter()
condition #measure this one? I do not like this!
t_conditionStop = perf_counter()
t_condition = t_conditionStop - t_conditionStart
...
...
t_stop = perf_counter()
total_time = t_stop - t_start
condition_percentage = t_condition / total_time
我不知道我是否遺漏了一些非常基本的東西。
對于那些對真正的 SAT 問題感興趣的人(使用 Z3-Py),代碼應該像這樣(或者更好地說:不應該去):
t_start = perf_counter()
...
t_satSearch = 0
s = Solver()
while s.check() == sat:
t_satSearchStart = perf_counter()
s.check() == sat #measure this one? I do not like this!
t_satSearchStop = perf_counter()
t_satSearch = t_satSearchStop - t_satSearchStart
...
...
t_stop = perf_counter()
total_time = t_stop - t_start
satSearch_percentage = t_satSearch / total_time
uj5u.com熱心網友回復:
在每次執行回圈之前檢查條件。因此,您需要做的就是在 4 個地方測量時間:
- 回圈前 (t0)
- 在回圈的開始 (t1)
- 就在回圈結束之前(t0)
- 在while回圈之后(t1)
這樣,您可以通過每次更新 t1 時檢查 t1-t0 的值來獲得每種可能情況下的執行時間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/447852.html
上一篇:宣告期間呼叫的查找映射函式
