memoize => Save/Restore Cache
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuesta aceptada
Jan
el 13 de En. de 2023
Editada: Jan
el 7 de Feb. de 2023
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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Data Type Identification en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!