การใช้ฟังก์ชัน tic toc ใน Matlab

ฉันมีสองวิธีที่ต่างกันในการใช้สิ่งเดียวกัน แต่ฉันเดาว่าวิธีที่สองนั้นดีที่สุด อย่างไรก็ตาม ฉันได้ผลลัพธ์ที่ดีขึ้นเมื่อใช้ 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))

person Babibel    schedule 13.09.2013    source แหล่งที่มา
comment
ค่อนข้างง่าย วิธีวนซ้ำของคุณนั้นเร็วกว่า   -  person Dan    schedule 13.09.2013
comment
@Dan ไม่มันไม่ใช่อย่างนั้น มันเร็วกว่าสำหรับเมทริกซ์ขนาดเล็ก ดูคำตอบของฉัน   -  person Mohsen Nosratinia    schedule 13.09.2013


คำตอบ (1)


ขึ้นอยู่กับว่ากลไก JIT ของ MATLAB สามารถปรับปรุงประสิทธิภาพของ 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
person Mohsen Nosratinia    schedule 13.09.2013