首页 > 解决方案 > 迭代模拟的严重性能问题

问题描述

我最近在实现模拟算法时偶然发现了一个性能问题。我设法找到了瓶颈函数(信号是内部调用arrayfun减慢了一切):

function sim = simulate_frequency(the_f,k,n)

    r = rand(1,n); % 
    x = arrayfun(@(x) find(x <= the_f,1,'first'),r);
    sim = (histcounts(x,[1:k Inf]) ./ n).';

end

它在代码的其他部分中使用如下:

h0 = zeros(1,sims);

for i = 1:sims
    p = simulate_frequency(the_f,k,n);
    h0(i) = max(abs(p - the_p));
end

以下是一些可能的值:

% Test Case 1
sims = 10000;
the_f = [0.3010; 0.4771; 0.6021; 0.6990; 0.7782; 0.8451; 0.9031; 0.9542; 1.0000];
k = 9;
n = 95;

% Test Case 2
sims = 10000;
the_f = [0.0413; 0.0791; 0.1139; 0.1461; 0.1760; 0.2041; 0.2304; 0.2552; 0.2787; 0.3010; 0.3222; 0.3424; 0.3617; 0.3802; 0.3979; 0.4149; 0.4313; 0.4471; 0.4623; 0.4771; 0.4913; 0.5051; 0.5185; 0.5314; 0.5440; 0.5563; 0.5682; 0.5797; 0.5910; 0.6020; 0.6127; 0.6232; 0.6334; 0.6434; 0.6532; 0.6627; 0.6720; 0.6812; 0.6901; 0.6989; 0.7075; 0.7160; 0.7242; 0.7323; 0.7403; 0.7481; 0.7558; 0.7634; 0.7708; 0.7781; 0.7853; 0.7923; 0.7993; 0.8061; 0.8129; 0.8195; 0.8260; 0.8325; 0.8388; 0.8450; 0.8512; 0.8573; 0.8633; 0.8692; 0.8750; 0.8808; 0.8864; 0.8920; 0.8976; 0.9030; 0.9084; 0.9138; 0.9190; 0.9242; 0.9294; 0.9344; 0.9395; 0.9444; 0.9493; 0.9542; 0.9590; 0.9637; 0.9684; 0.9731; 0.9777; 0.9822; 0.9867; 0.9912; 0.9956; 1.000];
k = 90;
n = 95;

标量sims必须在范围内1000 1000000。累积频率的向量the_f永远不会包含超过100元素。标量k表示 中的元素数the_f。最后,标量n表示经验样本向量中的元素数量,甚至可以非常大(10000据我所知,最多可达元素)。

有关如何改善此过程的计算时间的任何线索?

标签: matlabperformancesimulation

解决方案


在第二个测试用例中,这对我来说似乎要快一些,而不是第一个。对于更长the_f和更大的 值,时间差异可能会更大n

function sim = simulate_frequency(the_f,k,n)
    r = rand(1,n); % 
    [row,col] = find(r <= the_f); % Implicit singleton expansion going on here!
    [~,ind] = unique(col,'first');
    x = row(ind);
    sim = (histcounts(x,[1:k Inf]) ./ n).';
end

我在 中使用隐式单例扩展r <= the_fbsxfun如果您有旧版本的 MATLAB(但您知道练习),请使用。

rFind 然后将行和列返回到大于的所有位置the_funique为每列的第一个元素找到结果中的索引。

学分:Andrei Bobrov 在 MATLAB Answers 上


另一个选项(来自this other answer)有点短但也有点模糊IMO:

mask = r <= the_f;
[x,~] = find(mask & (cumsum(mask,1)==1));

推荐阅读