計算科学の典型的な状況は、数日/数週間/数か月連続して実行されるプログラムを持つことです。ハードウェア/OS の障害は避けられないため、通常はチェックポイントを利用します。つまり、プログラムの状態を時々保存します。失敗した場合は、最新のチェックポイントから再起動します。
チェックポイントを実装する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))