避免功能中的结构输入

时间:2014-01-29 15:20:58

标签: matlab

我的问题是:是否应该避免使用结构作为Matlab函数的输入(如果目标是获得最佳性能)?使用结构作为输入而不是其他类型的输入也存在内存问题吗?

作为一个简单的案例,最好是这样做:

function test1(struct)
    var1 = struct.a
    var2 = struct.b
    var3 = struct.c
    ...
end

或者做得更好:

function test2(a,b,c)
    var1 = a
    var2 = b
    var3 = c
    ...
end

修改

根据Dennis的答案,我检查了探查器内存以获得更多信息。这是结果(注意c = rand(1000)):

┌───────────────────┬─────┬──────────┬──────────┬────────────────┬──────────────┬───────────────┬───────────┐
│Function Name      │Calls│Total Time│Self Time*│Allocated Memory│Freed Memory  │Self Memory    │Peak Memory│
├───────────────────┼─────┼──────────┼──────────┼────────────────┼──────────────┼───────────────┼───────────┤
│testfun            │1    │14.332 s  │1.603 s   │39149952.00 Kb  │39149828.00 Kb│-23470220.00 Kb│7832.00 Kb │
├───────────────────┼─────┼──────────┼──────────┼────────────────┼──────────────┼───────────────┼───────────┤
│testfun>teststruct │1000 │2.815 s   │2.815 s   │7828000.00 Kb   │7828000.00 Kb │0.00 Kb        │7828.00 Kb │
├───────────────────┼─────┼──────────┼──────────┼────────────────┼──────────────┼───────────────┼───────────┤
│testfun>testcell   │1000 │2.800 s   │2.800 s   │7828000.00 Kb   │7828000.00 Kb │0.00 Kb        │7828.00 Kb │
├───────────────────┼─────┼──────────┼──────────┼────────────────┼──────────────┼───────────────┼───────────┤
│test (MEX-function)│1000 │2.396 s   │2.396 s   │7830000.00 Kb   │0.00 Kb       │7830000.00 Kb  │7832.00 Kb │
├───────────────────┼─────┼──────────┼──────────┼────────────────┼──────────────┼───────────────┼───────────┤
│testfun>testvars   │1000 │2.395 s   │2.395 s   │7828000.00 Kb   │7828.00 Kb    │7820172.00 Kb  │7828.00 Kb │
├───────────────────┼─────┼──────────┼──────────┼────────────────┼──────────────┼───────────────┼───────────┤
│testfun>testmix    │1000 │2.323 s   │2.323 s   │7828000.00 Kb   │7828.00 Kb    │7820172.00 Kb  │7828.00 Kb │
└───────────────────┴─────┴──────────┴──────────┴────────────────┴──────────────┴───────────────┴───────────┘

我不明白为什么结构和细胞功能的释放存活量比其他2个更多?

1 个答案:

答案 0 :(得分:1)

通常在编程时,做一些“简单”的事情。方式更快。在这种情况下,这似乎也适用。

这是一个函数,它调用带有struct的函数,带有struct的元素,以及单独的变量。第一个有点慢。

function testfun
load testfuninput
a=1;
b=2;
c=rand(100);
s.a=a;
s.b=b;
s.c=c;
tic
for t = 1:1000
    teststruct(s)
end
toc
tic
for t = 1:1000
    testmix(s.a,s.b,s.c)
end
toc
tic
for t = 1:1000
    testvars(a,b,c)
end
toc
end

function teststruct(s)
s.c = s.c+1;
end
function testmix(a,b,c)
c = c + 1;
end
function testvars(a,b,c)
c = c + 1;
end

会返回类似的内容:

Elapsed time is 0.026694 seconds.
Elapsed time is 0.014959 seconds.
Elapsed time is 0.014366 seconds.

因此,采用单独变量的函数更快。

话虽如此:即使你这么做很多次,也只需要几分之一秒。因此,对于任何非平凡的函数,影响运行时不应超过其他参数。


有趣的旁注:如果删除结构的赋值并只调用s.c_1;,则testvars的速度并没有真正改变。

相关问题