【发布时间】:2015-12-08 12:24:02
【问题描述】:
计算科学中的典型情况是让程序连续运行数天/数周/数月。由于硬件/操作系统故障是不可避免的,因此通常使用检查点,即不时保存程序的状态。如果发生故障,则从最新的检查点重新启动。
实现检查点的pythonic方法是什么?
For example,可以直接dump函数的变量。
另外,我正在考虑将此类函数转换为一个类(见下文)。函数的参数将成为构造函数的参数。构成算法状态的中间数据将成为类属性。 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))
【问题讨论】:
-
我认为你将长期运行的函数变成一个类的想法是个好主意。
-
如果你的长期运行函数的状态是明确定义的,那么你可以显式地存储它(如果需要,创建一个类并实现泡菜支持)。在更复杂的情况下可能会失败;除非你从头开始设计你的程序来支持它(Lisp,Smalltalk)¶ 要暂时断电,你可以hibernate your computer¶ 一般来说,你可以在 VM 中运行计算,然后 move it if necessary。在 docker 中有一个实验性的 checkpoint & restore 支持。
标签: python pickle checkpointing