2

matlab 構造体または matlab 変数 (任意の配列) から変数にアクセス/再割り当てするタイミングについて質問があります。

10 個の変数 (さまざまな次元とサイズの配列) を作成する 1 つの関数があるシナリオを想像してください。この関数は、これらの変数を生成する必要がある別の関数内で呼び出されています。

関数から 10 個の変数を取得するのは面倒なので、代わりにこれらの 10 個の変数を構造体に格納することを考え、最初の関数を変更して、10 個の変数ではなく 1 つの構造体 (10 個のフィールド) のみを出力するようにします。

タイミングは私にとって非常に重要なので (これは EEG 実験のコードです)、構造体のアプローチが遅くないことを確認したかったので、次のテスト関数を作成しました。

function test_timingStructs

%% define struct
strct.a=1; strct.b=2; strct.c=3;

%% define "loose" variables
a = 1; b = 2; c = 3;

%% How many runs?
runs = 1000;

%% time access to struct
x = []; % empty variable
tic
for i=1:runs
    x = strct.a; x = strct.b; x = strct.c;
end
t_struct = toc;

%% time access to "loose variables"
x = []; % empty variable
tic
for i=1:runs
    x = a; x = b; x = c;
end
t_loose = toc;

%% Plot results
close all; figure;
bar(cat(2,t_struct,t_loose));
set(gca,'xticklabel', {'struct', 'loose variable'})
xlabel('variable type accessed', 'fontsize', 12)
ylabel(sprintf('time (ms) needed for %d accesses to 3 different variables', runs), 'fontsize', 12)
title('Access timing: struct vs "loose" variables', 'fontsize', 15)

end

結果によると、構造体にアクセスしてフィールドの値を取得すると、変数にアクセスするよりもかなり遅くなります。私が行ったテストに基づいて、この仮定を立てることができますか?

アクセスしたいときに時間を失うことなく、10個の変数をきちんと「パッケージ化」する別の方法はありますか?

結果

4

1 に答える 1