计算科学中的典型情况是有一个连续运行几天/几周/几个月的程序。由于硬件/操作系统故障是不可避免的,因此通常使用检查点,即不时保存程序的状态。如果发生故障,则从最新的检查点重新启动。
实现检查点的pythonic方法是什么?
例如,可以直接转储函数的变量。
或者,我正在考虑将此类函数转换为一个类(见下文)。函数的参数将成为构造函数的参数。构成算法状态的中间数据将成为类属性。pickle
模块将有助于(反)序列化。
import pickle
# The file with checkpointing data
chkpt_fname = 'pickle.checkpoint'
class Factorial:
def __init__(self, n):
# Arguments of the algorithm
self.n = n
# Intermediate data (state of the algorithm)
self.prod = 1
self.begin = 0
def get(self, need_restart):
# Last time the function crashed. Need to restore the state.
if need_restart:
with open(chkpt_fname, 'rb') as f:
self = pickle.load(f)
for i in range(self.begin, self.n):
# Some computations
self.prod *= (i + 1)
self.begin = i + 1
# Some part of the computations is completed. Save the state.
with open(chkpt_fname, 'wb') as f:
pickle.dump(self, f)
# Artificial failure of the hardware/OS/Ctrl-C/etc.
if (not need_restart) and (i == 3):
return
return self.prod
if __name__ == '__main__':
f = Factorial(6)
print(f.get(need_restart=False))
print(f.get(need_restart=True))