与对象一起使用时,Matlab结构令人沮丧

时间:2013-08-02 23:54:48

标签: performance matlab oop struct

这是一个包含两个属性的简单类: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.

不仅性能下降了几个数量级,而且每次试验都有一个非常明显的趋势(更一般地证实)放慢速度。我不明白。此外,如果我改为使用一个独立的未初始化的struct数组,它不是一个对象属性(这一行替换了循环中的那一行):

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.

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

1 个答案:

答案 0 :(得分: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

慢速返回。