MATLAB传递值与对象的值

时间:2013-07-31 23:45:58

标签: performance matlab oop parameter-passing

有人可以解释为什么会有显着的时差吗?

function [] = maincalc ()

ak=am();

t1=tic;
[out] = myfun (ak.aa, ak.b, ak.c, ak.d, ak.e, ak.f, ak.g, ak.h);
to1end=toc(t1)

t2=tic;
[out2] = myfun2 (ak);
to2end=toc(t2)

结果:

to1end =
   0.047520231560659
to2end =  
  12.490895284055467

class am(我知道有人可能会说没有理由为此使用类,但整个代码是一个更复杂和更长的代码的简化,并且类是必要的):

classdef am 
    properties
        aa = 1;
        b = 2;
        c = 3;
        d = 4;
        e = 2.3;
        f = 4.2;
        g = 5.09;
        h = 12.3;
    end
end

功能myfun:

function [out] = myfun (aa, b, c, d, e, f, g, h)
n = 500000;
i = 0; j = 0; k = 0; l = 0;
for s = 1:n
    i = aa/b + j*k - i;
    j = c/d ^ 0.5 - j / i;
    k = e*f + aa/3 - k/8;
    l = g + exp (h) + l ^ -1;
end
out.i = i;
out.j = j;
out.k = k;
out.l = l;

功能myfun2:

function [out] = myfun2 ( ak )
n = 500000;
i = 0; j = 0; k = 0; l = 0;
for s = 1:n
    i = ak.aa/ak.b + j*k - i;
    j = ak.c/ak.d ^ 0.5 - j / i;
    k = ak.e*ak.f + ak.aa/3 - k/8;
    l = ak.g + exp (ak.h) + l ^ -1;
end
out.i = i;
out.j = j;
out.k = k;
out.l = l;

我已经读过某人解释有关MATLAB的写时复制的内容,但这并不适用于此,因为没有对该类的任何成员进行任何更改。

=============================================== =================================== 此行下方的详细信息最近于2013年8月2日添加

Marcin回应说,它与MATLAB将参数传递给函数的方式没什么关系(顺便说一句,很棒的发现!),但我认为它仍然与它有关。我已经制作了另一个代码,这次所有三种方法都需要多次访问该类:

function [] = maincalc3 ()

inputvar=inputclass();

to1end = 0;
to2end = 0;
to3end = 0;
j = 100;

for i = 1:j;
    t1=tic;
    [out] = func1 (inputvar);
    to1end=toc(t1) + to1end;

    t2=tic;
    [out2] = func2 (inputvar.s);
    to2end=toc(t2) + to2end;

    t3=tic;
    [out3] = func3 (inputvar);
    to3end=toc(t3) + to3end;
end

..............................

classdef inputclass
    properties
        s  = 1;
    end
end

...............................

function f = func1 (inputvar)
    f = inputvar.s;
end

...............................

function f = func2 (s)
    f = s;
end

...............................

function [f] = func3 (inputvar)
    s=inputvar.s;
    f = s;
end

结果:

to1end =
   0.002419525505078
to2end =
   0.001517134538850
to3end =
   0.002353777529397

func1()func3()大约需要相同的时间,但func2的时间减少约60%。这是否意味着MATLAB将参数传递给函数的方式 - 通过值或对象 - 确实会影响性能?

1 个答案:

答案 0 :(得分:4)

我认为与按值或引用将对象传递给函数没什么关系。它只是因为在你的循环中,在myfun2() matlab需要多次访问对象及其字段。而已。

例如,如果您按如下方式创建名为myfun3()的第三个函数:

function [out] = myfun3 (ak)
n = 500000;
i = 0; j = 0; k = 0; l = 0;

% FOLLOWING LINE IS NEW <-----
% REMOVE object refencese from within the loop and create local variables
% to use in the loop, instead of referencing object properties all the time.
aa = ak.aa; b = ak.b; c=ak.c; d=ak.d; e=ak.e; f=ak.f; g=ak.g; h=ak.h;

for s = 1:n
    i = aa/b + j*k - i;
    j = c/d ^ 0.5 - j / i;
    k = e*f + aa/3 - k/8;
    l = g + exp (h) + l ^ -1;
end
out.i = i;
out.j = j;
out.k = k;
out.l = l;

此功能的执行速度甚至比myfun1()略快。在我的电脑上,结果是:

to1end =

    0.0533


to2end =

   23.9410


to3end =

    0.0526 % RESULT for myfun3() function