2

这是一个具有两个属性的简单类: PStruct 是一个包含结构的属性。

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.

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

4

1 回答 1

1

很奇怪。

我发现如果您执行以下任一操作,代码将恢复正常速度

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

或者

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

但是如果你使用 double 代码仍然很慢

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

慢速回归。

于 2013-08-03T09:56:03.503 回答