[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: My vectorized code is slower than a loop

From: Dave Cottingham
Subject: Re: My vectorized code is slower than a loop
Date: Thu, 20 Oct 2016 10:50:43 -0400

I had come to a similar conclusion, from looking at (and reproducing) Nicholas' timing results. In my original vectorized version, the operations spent computing the index ranges are more than what's saved by vectorizing. I did some precomputing of the ranges, similar to yours, and managed to get the vectorized version no slower than the loop.

As dismaying as that is, I think I see why: at each i, the number of things copied is a few or none, so there's nothing to be gained by vectorizing. This code fragment can only be sped up by eliminating the loop on i -- and I see no way to do that.

My conclusion is there's no alternative to implementing this is c++ (which I've already done).

Dave Cottingham

On Wed, Oct 19, 2016 at 4:19 PM, Francesco Potortì <address@hidden> wrote:
No profiling, no runs, just looking at the code, so I may be off.

w = zeros(1, n);
j = 1
for i = 1:n
  if (vectorised)
    if(left(i) <= right(i))
      w(j:j+right(i)-left(i)) = x(i) - x(n+1-[left(i):right(i)]);
      j = j + right(i)-left(i)+1;
  else                          # looping
    if(left(i) <= right(i))
      for jj = left(i):right(i)
        w(j) = x(i) - x(n+1-jj);
        j += 1;

In the loop version, the if is useless, because the for range will be
empty, so the for will not run when the if clause is false.  This may
result in a speedup or not.

In the vectorised version, I would write it like this, which minimises
the number of operations at the expense of the number of instructions,
which may result in a speedup or not:

   li = left(i);
   d = right(i) - li;
   if (d >= 0)
     dr = 0:d;
     w(j+dr) = x(i) - x(n+1-li+dr);
     j += d+1;

Francesco Potortì (ricercatore)        Voice:  +39.050.621.3058
ISTI - Area della ricerca CNR          Mobile: +39.348.8283.107
via G. Moruzzi 1, I-56124 Pisa         Skype:  wnlabisti
(entrance 20, 1st floor, room C71)     Web:

reply via email to

[Prev in Thread] Current Thread [Next in Thread]