menggunakan fungsi tic toc di matlab

Saya memiliki dua cara berbeda untuk menerapkan hal yang sama tetapi menurut saya cara kedua adalah yang terbaik. Namun, saya mendapatkan hasil yang lebih baik saat menggunakan tic toc untuk pertama kalinya. Bagaimana bisa ?

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

person Babibel    schedule 13.09.2013    source sumber
comment
Cukup sederhana, metode loop Anda lebih cepat.   -  person Dan    schedule 13.09.2013
comment
@Dan Tidak, bukan itu masalahnya. Ini lebih cepat untuk matriks kecil. Lihat jawaban saya.   -  person Mohsen Nosratinia    schedule 13.09.2013


Jawaban (1)


Itu tergantung pada bagaimana mesin JIT MATLAB dapat meningkatkan kinerja for loop. Untuk matriks kecil ini berfungsi dengan baik tetapi untuk matriks besar tidak berfungsi dengan baik. Tampaknya untuk i kurang dari 60, metode pertama lebih cepat, tetapi tidak untuk matriks yang lebih besar. Coba tolok ukur ini

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

Di mesin saya, ia kembali:

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
person Mohsen Nosratinia    schedule 13.09.2013