且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Cellfun 与简单的 Matlab 循环性能

更新时间:2023-09-15 19:35:52

如果性能是一个主要因素,您应该避免使用单元格、循环或 cellfun/arrayfun.使用向量操作通常要快得多(假设这是可能的).

If performance is a major factor you should avoid using cells, loops or cellfun/arrayfun. It's usually much quicker to use a vector operation (assuming this is possible).

下面的代码扩展了 Werner 的 add 示例,其中包含标准数组循环和数组操作.

The code below expands on Werner's add example with standard array loop and array operations.

结果是:

  • 单元格循环时间 - 0.1679
  • Cellfun 时间 - 2.9973
  • 循环阵列时间 - 0.0465
  • 阵列时间 - 0.0019

代码:

nTimes = 1000;
nValues = 1000;
myCell = repmat({0},1,nValues);
output = zeros(1,nValues);

% Basic operation
tic;
for k=1:nTimes
  for m=1:nValues
    output(m) = myCell{m} + 1;
  end
end
cell_loop_timeAdd=toc;    
fprintf(1,'Cell Loop Time %0.4f
', cell_loop_timeAdd);

tic;        
for k=1:nTimes
  output = cellfun(@(in) in+1,myCell);
end
cellfun_timeAdd=toc;
fprintf(1,'Cellfun Time %0.4f
', cellfun_timeAdd);


myData = repmat(0,1,nValues);
tic;
for k=1:nTimes
  for m=1:nValues
    output(m) = myData(m) + 1;
  end
end
loop_timeAdd=toc;
fprintf(1,'Loop Array Time %0.4f
', loop_timeAdd);

tic;
for k=1:nTimes
    output = myData + 1;
end
array_timeAdd=toc;
fprintf(1,'Array Time %0.4f
', array_timeAdd);