python - 为什么我的 Python 计时器类不起作用?
问题描述
我编写了自己的课程来测量脚本不同部分的时间:
class SimulationTimer:
accumulated_elapsed_time = 0.0
def __init__(self):
self._simulation_start_time = None
self._simulation_stop_time = None
def start(self):
"""start a new timer"""
if self._simulation_start_time is not None: # attribute
raise TimeError(f"Timer is running.\n Use .stop() to stop it")
self._simulation_start_time = time.perf_counter()
def stop(self):
"""stop the time and report the elsaped time"""
if self._simulation_start_time is None:
raise TimeError(f"Timer is not running.\n Use .start() to start it.")
self._simulation_stop_time = time.perf_counter()
elapsed_simulation_time = self._simulation_stop_time - self._simulation_start_time
self.accumulated_elapsed_time += elapsed_simulation_time # Isn't accumulating values of times.
self._simulation_start_time = None
print(f"Elapsed time: {elapsed_simulation_time:0.10f} seconds")
def get_accumulated_time(self):
""" Return the elapsed time for later use"""
return self.accumulated_elapsed_time
我试图在不同的内核上多次运行随机模拟,然后绘制并测量array1
在array2
我使用multiprocessing
pool
方法运行的不同内核上运行模拟所需的时间。使用以下代码:
def func(*args):
t = SimulationTimer()
t.start()
Do stuff
t.stop()
print(f"Accumulated time: {t.get_accumulated_time():0.10f} seconds")
return array1, array2, t.accumulated_elapsed_time
array1, array2, accumulated_elapsed_time = gillespie_tau_leaping(start_state, LHS, stoch_rate, state_change_array)
需要上面的行,因此可以将 array1 和 array2 传递给绘图函数
if __name__ == '__main__':
with Pool() as p:
pool_results = p.map(func, [*args])
print(f"Total time:\n {sum(pool_results)}")
def gillespie_plot(array1, array2):
fig, ax = plt.subplots()
for i, label in enumerate(['Enzyme', 'Substrate', 'Enzyme-Substrate complex', 'Product']):
ax.plot(array2, array1[:, i], label=label)
ax.legend()
plt.show()
return fig
gillespie_plot(array1, array2)
但accumulate_elapsed_time
似乎没有工作。它为每个进程返回 4 个单独的时间,而不是将所有进程的值累积到总时间中。
我哪里错了?
编辑:有人建议accumulated_elapsed_time = 0.0
从实例编辑到class
变量并从我的函数返回t.accumulated_elapsed_time
,我已经这样做了,但它似乎仍然不起作用?
解决方案
accumulate_elapsed_time
是一个实例变量,所以每个多进程都在重新创建它。accumulate_elapsed_time
必须是类变量。
推荐阅读
- linkedin - 在对 Linkedin V2 API 的请求中总是返回哪个名字字段?
- google-analytics - Bigquery - 计算添加到购物车的数量
- c++ - 使用 C++ 中的 Lua,无法打开标准库并出现 Nil 错误
- asp.net - 如何使用 ASP.NET MVC 中的请求标头对具有 Oauth2 授权的 API 进行 HTTP get 调用?
- angular - Angular 材质中的奇怪行为
- c++ - 如何判断当前进程是否已经锁定了一个文件?
- javascript - 不知道密钥的通用过滤器功能
- json - 抄送文件给第三方发送给签名者,仅在信封中查看
- javascript - 如何通过filestack上传大文件?
- shell - 如何在特定单词之后交换单词,可以在一行中,也可以使用 sed 在不同行中?