2

有人可以解释为什么会有很大的时差吗?

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(我知道有人可能会说没有理由为此使用 class,但是整个代码是对更复杂和更长的代码的简化,并且 class 是必要的):

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

功能我的乐趣:

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 将参数传递给函数的方式——通过值或对象——会影响性能?

4

1 回答 1

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
于 2013-08-01T00:10:45.923 回答