您可能想要考虑的另一种技术是检查点。我已经使用类似于长时间运行(超过一天)的循环,这些循环在机器可能随时变得不可用的环境中运行,例如在实验室中分布的备用机器集群。
基本上,在开始循环之前,检查是否存在“检查点”文件。如果确实如此,那么上次循环没有成功完成。它包含有关循环起作用的信息以及您需要再次进行的任何其他状态。
这是一个简化的例子:
function myFunction()
numIter = 10;
startIter = 1;
checkpointFilename = 'checkpoint.mat';
% Check for presence of checkpoint file suggesting the last run did not
% complete
if exist(checkpointFilename, 'file')
s = load(checkpointFilename);
startIter = s.i;
fprintf('Restarting from iteration %d\n', startIter);
end
for i = startIter:numIter
fprintf('Starting iteration %d\n', i);
expensiveComputation();
save(checkpointFilename, 'i');
end
% We succefully finished. Let's delete our checkpoint file
delete(checkpointFilename);
function expensiveComputation()
% Pretend to do lots of work!
pause(1);
end
end使用ctrl-c部分运行和突破看起来像这样:
>> myFunction
Starting iteration 1
Starting iteration 2
Starting iteration 3
Starting iteration 4
Operation terminated by user during myFunction/expensiveComputation (line 27)
In myFunction (line 18)
expensiveComputation();
>> myFunction
Restarting from iteration 4
Starting iteration 4
Starting iteration 5
...