我对从 matlab 结构或 matlab 变量(任何数组)访问/重新分配变量时的时间有疑问:
想象一下,您有一个创建十个变量(不同维度和大小的数组)的函数。该函数在另一个需要生成这些变量的函数中被调用。
现在,因为从函数中获取十个变量看起来很麻烦,所以我考虑将这十个变量存储在一个结构中,并更改我的初始函数,使其仅输出一个结构(有十个字段)而不是十个变量。
因为时间对我来说至关重要(它是 EEG 实验的代码),我想确保 struct 方法不慢,所以我编写了以下测试函数。
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
根据结果,访问结构以获取字段的值比仅访问变量要慢得多。我可以根据我所做的测试做出这个假设吗?
当我想访问它们时,是否有另一种方法可以巧妙地“打包”十个变量而不会浪费时间?