Main Content

Unrollfor-Loops andparfor-Loops

When the code generator unrolls afor-loop orparfor-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.

Forcefor-Loop Unrolling by Usingcoder.unroll

代码生成器使用启发式来确定when to unroll afor-loop. To force loop unrolling, usecoder.unroll. This affects only theforloop that is immediately aftercoder.unroll. For example:

functionz = call_myloop()%#codegenz = myloop(5);endfunctionb = myloop(n) b = zeros(1,n); coder.unroll();fori = 1:n b(i)=i+n;endend

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 afor-loop is unrolled, use thecoder.unrollflagargument. For example, unroll the loop only when the number of iterations is less than 10.

functionz = call_myloop()%#codegenz = myloop(5);endfunctionb = myloop(n) unroll_flag = n < 10; b = zeros(1,n); coder.unroll(unroll_flag);fori = 1:n b(i)=i+n;endend

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

functionb = myloop(n) b = zeros(1,n); coder.unroll();fori = 1:n b(i)=i+n;endend

See Also

Related Topics