2013-08-02 41 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