Main Content

Unroll for-Loops and parfor-Loops

When the code generator unrolls a for-loop or parfor-loop, instead of producing a loop in the generated code, it produces a copy of the loop body for each iteration. For small, tight loops, unrolling can improve performance. However, for large loops, unrolling can significantly increase code generation time and generate inefficient code.

Force for-Loop Unrolling by Using coder.unroll

The code generator uses heuristics to determine when to unroll a for-loop. To force loop unrolling, use coder.unroll. This affects only the for loop that is immediately after coder.unroll. For example:

function z = call_myloop()
%#codegen
z = myloop(5);
end

function b = myloop(n)
b = zeros(1,n);
coder.unroll();
for i = 1:n
    b(i)=i+n;
end
end

Here is the generated code for the for-loop:

  z[0] = 6.0;
  z[1] = 7.0;
  z[2] = 8.0;
  z[3] = 9.0;
  z[4] = 10.0;

To control when a for-loop is unrolled, use the coder.unroll flag argument. For example, unroll the loop only when the number of iterations is less than 10.

function z = call_myloop()
%#codegen
z = myloop(5);
end

function b = myloop(n)
unroll_flag = n < 10;
b = zeros(1,n);
coder.unroll(unroll_flag);
for i = 1:n
    b(i)=i+n;
end
end

To unroll a for-loop, the code generator must be able to determine the bounds of the for-loop. For example, code generation fails for the following code because the value of n is not known at code generation time.

function b = myloop(n)
b = zeros(1,n);
coder.unroll();
for i = 1:n
    b(i)=i+n;
end
end

See Also

Related Topics