0

我有这两种不同的方法来实现相同的东西,但我想第二种是最好的。但是,第一次使用 tic toc 时我得到了更好的结果。怎么会 ?

j=6;
i=j;
Savings = zeros(i,j);
Costs = magic(400);

tic;
for x=2:i
   for y=2:j
     if(x ~= y)
       Savings(x,y) = Costs(x,1) + Costs(1,y) - Costs(x,y);
     end
   end
end
first=toc;

disp(num2str(first))

Savings = zeros(i,j);

tic;
Ix=2:i; 
Iy=2:j;
I = false(i,j);
I(Ix,Iy) = bsxfun(@ne, Ix', Iy);
S = bsxfun(@plus, Costs(Ix,1), Costs(1,Iy)) - Costs(Ix,Iy);
Savings(I) = S(I(Ix,Iy));
second=toc;

temp = Savings;
disp(num2str(second))
4

1 回答 1

6

这取决于 MATLAB 的 JIT 引擎如何提高for循环的性能。对于小型矩阵,它可以正常工作,但对于大型矩阵则不然。似乎i小于 60,第一种方法更快,但不适用于更大的矩阵。试试这个基准

for j=[6 30 60 100 200 400 600]
    disp(['j=' num2str(j)]);
    i=j;
    Savings = zeros(i,j);
    Costs = magic(600);

    tic;
    for mm=1:1e2
        for x=2:i
            for y=2:j
                if(x ~= y)
                    Savings(x,y) = Costs(x,1) + Costs(1,y) - Costs(x,y);
                end
            end
        end
    end
    first=toc;

    disp(num2str(first));

    Savings = zeros(i,j);

    tic;
    for mm=1:1e2
        Ix=2:i;
        Iy=2:j;
        I = false(i,j);
        I(Ix,Iy) = bsxfun(@ne, Ix', Iy);
        S = bsxfun(@plus, Costs(Ix,1), Costs(1,Iy)) - Costs(Ix,Iy);
        Savings(I) = S(I(Ix,Iy));
    end
    second=toc;

    temp = Savings;
    disp(num2str(second))
end

在我的机器上,它返回:

j=6
0.0001874
0.0052893
j=30
0.0034454
0.0057184
j=60
0.011097
0.01268
j=100
0.027957
0.023952
j=200
0.11529
0.058686
j=400
0.45791
0.37246
j=600
1.1496
0.74932
于 2013-09-13T11:06:20.133 回答