2013-08-02 17 views
2

下面是一个简单的具有两个属性的类:PStruct是一个包含结构的属性。Matlab结构与对象一起使用时的惨淡表现

classdef anobj < handle 
    properties 
     PStruct 
     PNum=1; 
    end 
    methods 
     function obj = anobj() 
     end 
    end 
end 

这里是一个脚本填充在一个对象中的结构用1的(相当快):

clear all 
a = anobj(); % an object 
b = anobj(); % another object for future use 
ntrials=10; niterations=1000; 
a.PStruct(ntrials,niterations).field1=0; % 'initialize' the struct array 
for t=1:ntrials 
    tic; 
    for i=1:niterations 
     a.PStruct(t,i).field1=1; % store data 
    end 
    toc; 
end 

得到:

Elapsed time is 0.001008 seconds. 
Elapsed time is 0.000967 seconds. 
Elapsed time is 0.000972 seconds. 
Elapsed time is 0.001206 seconds. 
Elapsed time is 0.000992 seconds. 
Elapsed time is 0.000981 seconds. 
Elapsed time is 0.000975 seconds. 
Elapsed time is 0.001072 seconds. 
Elapsed time is 0.000951 seconds. 
Elapsed time is 0.000994 seconds. 

当代替我用另一对象的属性( = 1),将循环内的行更改为:

a.PStruct(t,i).field1=b.PNum; % store data 

我得到:

Elapsed time is 0.112418 seconds. 
Elapsed time is 0.107359 seconds. 
Elapsed time is 0.118347 seconds. 
Elapsed time is 0.127111 seconds. 
Elapsed time is 0.138606 seconds. 
Elapsed time is 0.152675 seconds. 
Elapsed time is 0.162610 seconds. 
Elapsed time is 0.172921 seconds. 
Elapsed time is 0.184254 seconds. 
Elapsed time is 0.190802 seconds. 

不仅表现为数量级的速度较慢,但​​也有明显放缓,每个试验的一个很明显的趋势(验证更普遍)。我不明白。此外,如果我改用一个独立的初始化结构数组,它是不是一个对象的属性(这条线取代了环内的一个):

PStruct(t,i).field1=b.PNum; % store data 

我得到好的性能没有趋势:

Elapsed time is 0.007143 seconds. 
Elapsed time is 0.004208 seconds. 
Elapsed time is 0.004312 seconds. 
Elapsed time is 0.004382 seconds. 
Elapsed time is 0.004302 seconds. 
Elapsed time is 0.004545 seconds. 
Elapsed time is 0.004499 seconds. 
Elapsed time is 0.005840 seconds. 
Elapsed time is 0.004210 seconds. 
Elapsed time is 0.004177 seconds. 

结构数组和对象之间存在一些奇怪的相互作用。有人知道发生了什么,以及如何解决这个问题?谢谢。

回答

1

很奇怪。

我发现,如果你执行下列操作的代码返回到正常速度

c = b.PNum; 
a.PStruct(t,i).field1=c; % store data 

a.PStruct(t,i).field1=int32(b.PNum); % store data 

,但如果使用双代码仍然缓慢

a.PStruct(t,i).field1=double(b.PNum); % store data 

如果同时使用“快速”方法

c = b.PNum; 
a.PStruct(t,i).field1=c; % store data 
a.PStruct(t,i).field1=int32(b.PNum); % store data 

慢速回报。

+0

这很有趣。在某些情况下,将分配分配给两个命令可能对我有所帮助。谢谢。 – matfan001