Faster subscripting

by malcolm on March 9, 2010

in MATLAB

Subscripting is one of the most powerful M-Language features, a feature that differentiates it from most other languages. In this post we show a small language tweak can speed up some cases of subscripting.

When subscripting, which of the following MATLAB statements performs best?

A(1:n)
A(1:end)

It turns out that in both Jacket and standard MATLAB the latter is faster. In fact, any subscripting you do should make use of that end keyword if possible: A(1:end), A(1:end-1).

Here’s what’s happening. When 1:n is used in MATLAB, it gets expanded out in memory by MATLAB. When MATLAB then goes to use it in the subscript, it has to look at each element individually as it processes the indexing. In contrast, with the 1:end syntax, both Jacket and MATLAB avoid the intermediate expansion and just start executing the indexing assuming a linear sequence.

Let’s do some timings. Here’s the Jacket version…

n = 1e4;
reps = 10000;

% warm up
A = grand(1,n);
b = A(500:end);
b = A(500:n);

gsync;
tic;
   for r = 1:reps
     b = A(500:end);  geval(b);
   end
gsync;
gpu_end = toc / reps * 1e6

gsync;
tic;
   for r = 1:reps
     b = A(500:n);    geval(b);
   end
gsync;
gpu_n = toc / reps * 1e6  % microseconds

This gives a speedup of about 2.3x on my laptop — for both the CPU and GPU versions.

Comments on this entry are closed.

blog comments powered by Disqus

Previous post:

Next post: