Loren on the Art of MATLAB

Turn ideas into MATLAB

Note

Loren on the Art of MATLABhas been retired and will not be updated.

有关子阵列计算速度的最新问题

最近,有人要求我解释使用循环和阵列索引进行计算的速度行为,而不是先获取子阵列。

Contents

Example

Suppose I have a function of two inputs, the first input being the column (of a square array), the second, a scalar, and the output, a vector.

myfun = @(x,z)x'*x+z;

And even though this may be calculated in a fully vectorized manner, let's explore what happens when we work on subarrays from the array input.

I am now creating the input arrayx结果输出以完成计算的阵列两种方式,其中一种方法中有一个中间步骤。

n = 500;x = randn(n,n);结果1 =零(n,1);结果2 =零(n,1);

第一个方法

Here we see and time the first method. In this one, we create a temporary array forx(:,k)ntimes through the outer loop.

ticfork = 1:nforz = 1:n result1(z)= myFun(x(:,k),z);endresult1 = result1+x(:,k);endruntime(1) = toc;

第二种方法

In this method, we extract the column of interest first in the outer loop, and reuse that temporary array each time through the inner loop. Again we see and time the results.

ticfork = 1:nxt = x(:,k);forz = 1:n result2(z) = myfun(xt, z);endresult2 = result2+x(:,k);endruntime(2) = toc;

Same Results?

首先,让我们确保两种方式得到相同的答案。您可以看到我们这样做。

thesame = is equal(结果1,result2)
theSame = 1

Compare Runtime

接下来,让我们比较时间。我想提醒您,从脚本进行计时通常比在函数中运行相同代码时的开销更多。我们只想看到相对行为,因此我们应该从本练习中获得一些见解。

disp([[“运行时间是:”,num2str(运行时)])
Run times are: 2.3936 1.9558

What's Happening?

Here's what's going on. In the first method, we create a temporary variablentimes through the outer loop, even though that array is a constant for a fixed column. In the second method, we extract the relevant column once, and reuse itntimes through the inner loop.

Be thoughtful if you do play around with this. Depending on the details of your function, if the calculations you do each time are large compared to the time to extract a column vector, you may not see much difference between the two methods. However, if the calculations are sufficiently short in duration, then the repeated creation of the temporary variable could add a tremendous amount of overhead to the calculation. In general, you should not be worse off always capturing the temporary array the fewest number of times possible.

您的结果?

Have you noticed similar timing "puzzles" when analyzing one of your algorithms? I'd love to hear more这里.




Published with MATLAB® R2013a

|