Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MATLAB结构似乎很慢_Matlab_Performance_Function_Structure - Fatal编程技术网

MATLAB结构似乎很慢

MATLAB结构似乎很慢,matlab,performance,function,structure,Matlab,Performance,Function,Structure,在我的代码中,我必须将几个大数组传递给一个函数,为了简化可读性,我使用了一个结构,我称它为params。具体而言: params.grid1 = grid1; params.grid2 = grid2; % these are big arrays % etc. % Define x y = myfun(x,params) function y = myfun(x,params) y = x+params.grid2; end 但是,我注意到下面的代码要快得多: params.g

在我的代码中,我必须将几个大数组传递给一个函数,为了简化可读性,我使用了一个结构,我称它为
params
。具体而言:

params.grid1 = grid1;
params.grid2 = grid2; % these are big arrays
% etc.

% Define x

y = myfun(x,params)


function y = myfun(x,params)
   y = x+params.grid2;
end
但是,我注意到下面的代码要快得多:

params.grid1 = grid1;
params.grid2 = grid2; % these are big arrays
% etc.

% Define x

y = x+params.grid2;
代码的第一个版本中的函数调用似乎显著降低了性能。不幸的是,对于我的项目,我无法避免使用函数(否则将是一团糟)。我认为将结构传递给函数是一种快速的选择。关于如何提高速度有什么建议吗

这里是一个MWE:

%% Passing matlab structures to function seems to be slow

clear;clc;close all

n = 100000;

rng('default')
grid1 = rand(n,1);
grid2 = rand(n,1);
params.grid1 = grid1;
params.grid2 = grid2; % these are big arrays
% etc.
% Define x
%% disp('Testing code 1 - passing struct to a function')
tic
x = 3;
[y1,y2] = myfun(x,params);
y1
y2
toc

%% disp('Testing code 2 - no function')
tic

x = 3;
y1 = mean(x+(params.grid1).^2);
y2 = mean(x+(params.grid2).^2);



 y1
 y2

toc
要运行它,您还需要以下功能:

function [y1,y2] = myfun(x,params)
   y1 = mean(x+(params.grid1).^2);
   y2 = mean(x+(params.grid2).^2);


end
代码1(将结构传递给函数):运行时间为0.001682秒。 代码2(不向函数传递结构):运行时间为0.000737秒


在测试之前,我按照建议运行了几次代码。

如果您真的想要速度,请避免使用结构。另外,你能做一个实验来显示这种行为吗?你是如何测量速度的?我用toc来测量速度,不要用
tic
toc
。这是非常不准确的,可能会产生误导。始终将要计时的代码粘贴到函数中(以便JIT可以完成它的任务),并使用
timeit
来计时函数的执行
timeit
将多次运行该函数,并且编译时间不会影响计时。特别是,第一次调用函数时,将加载并编译该函数,这将导致时间损失。第二次调用该函数时,速度会快得多。因此,在使用
tic
/
toc
构造计时之前,至少运行函数一次。创建一个函数M-file,其中包含两个私有函数:
method1
method2
。它们都需要接受
x
params
数组,并返回
y1
y2
数组。在主函数中,执行
timeit(@()方法1(x,参数))
timeit(@()方法2(x,参数))
。这将使您很好地了解调用函数的开销。