29.10.2014 Views

ARM Compiler toolchain v4.1 for µVision Using the Compiler

ARM Compiler toolchain v4.1 for µVision Using the Compiler

ARM Compiler toolchain v4.1 for µVision Using the Compiler

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Compiler</strong> Coding Practices<br />

5.5 Optimization of loop termination in C code<br />

Loops are a common construct in most programs. Because a significant amount of execution<br />

time is often spent in loops, it is worthwhile paying attention to time-critical loops.<br />

The loop termination condition can cause significant overhead if written without caution. Where<br />

possible:<br />

• use simple termination conditions<br />

• write count-down-to-zero loops<br />

• use counters of type unsigned int<br />

• test <strong>for</strong> equality against zero.<br />

Following any or all of <strong>the</strong>se guidelines, separately or in combination, is likely to result in better<br />

code.<br />

Table 5-1 shows two sample implementations of a routine to calculate n! that toge<strong>the</strong>r illustrate<br />

loop termination overhead. The first implementation calculates n! using an incrementing loop,<br />

while <strong>the</strong> second routine calculates n! using a decrementing loop.<br />

Table 5-1 C code <strong>for</strong> incrementing and decrementing loops<br />

Incrementing loop<br />

int fact1(int n)<br />

{<br />

int i, fact = 1;<br />

<strong>for</strong> (i = 1; i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!