首页 > 解决方案 > 为什么我的 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

我试图在不同的内核上多次运行随机模拟,然后绘制并测量array1array2我使用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 ,我已经这样做了,但它似乎仍然不起作用?

标签: pythonclasstimemultiprocessing

解决方案


accumulate_elapsed_time是一个实例变量,所以每个多进程都在重新创建它。accumulate_elapsed_time必须是类变量。


推荐阅读