memoize => Save/Restore Cache
조회 수: 3 (최근 30일)
이전 댓글 표시
Hi,
would it be possible to Save and Restore the memoize Cache?
Calculating the cache would take 4min and it would be easier to load it from a file since i use it daily.
I found this to read the cache but nothing to restore it
>> s = stats(mfCR);
>> s.Cache.Inputs{:};
Thanks for your responds
Benno
댓글 수: 0
채택된 답변
Jan
2023년 1월 13일
편집: Jan
2023년 2월 7일
There is no documented way to store the cache. But it is cheap to create a look-up table for your function and store it manually. This uses GetMD5 for hashing the inputs:
function varargout = FcnLUT(fcn, varargin)
% Cache output of function for specific input
% varargout = FcnLUT(fcnName, varargin)
% INPUT:
% fcn: Function handle or name of the function as CHAR vector.
% Special commands: 'clear', 'save', 'load' to manage the cache.
% varargin: Arguments of the function.
% OUTPUT:
% Same output as: fcnName(varargin{:})
%
% EXAMPLE:
% tic; x = FcnLUT(@(x,y) exp(x:y), 1, 1e8); toc
% tic; x = FcnLUT(@(x,y) exp(x:y), 1, 1e8); toc
% The 2nd call is much faster, because the output is copied from the cache.
% Huge input arguments slow down the caching, because calculating the hash of
% the data is expensive. Example:
% tic; x = FcnLUT(@exp, 1:1e8); toc % Tiny advantage only!
%
% Tested: Matlab 2009a, 2015b(32/64), 2016b, 2018b, Win10
% Author: Jan Simon, Heidelberg, (C) 2023
% Dependency: https://www.mathworks.com/matlabcentral/fileexchange/25921-getmd5
% $License: BSD (use/copy/change/redistribute on own risk, mention the author) $
% History:
% 001: 13-Jan-2023 17:24, First version.
% Initialize: ==================================================================
persistent LUT
if isempty(LUT)
LUT = struct();
end
% Manage the cache: ============================================================
if nargin == 1
dataFile = fullfile(fileparts(mfilename('fullpath')), 'FcnLUT.mat');
switch lower(fcn)
case 'clear'
LUT = struct();
case 'save'
save(dataFile, '-struct', 'LUT');
case 'load'
if isfile(dataFile)
LUT = load(dataFile);
end
otherwise
error(['Jan:', mfilename, ':BadCommand'], ...
'Unknown command: %s', fcn);
end
return;
end
% Get answer from cache or perform the calculations: ===========================
H = ['H_', GetMD5({fcn, varargin}, 'Array', 'hex')];
if isfield(LUT, H)
varargout = LUT.(H);
else
[varargout{1:nargout}] = feval(fcn, varargin{:});
LUT.(H) = varargout;
end
end
Finally, this is a replacement for the memoize() function.
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Identification에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!