memoize => Save/Restore Cache

3 ビュー (過去 30 日間)
Benno Maul
Benno Maul 2023 年 1 月 12 日
編集済み: Jan 2023 年 2 月 7 日
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

採用された回答

Jan
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 件)

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

タグ

製品


リリース

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by