3.2. Using Optimizations

So far we've used the default level of optimization. This is fine for small example programs such as hello.c. But for a production-quality application program we should use optimization level 2. We will still be able to debug programs compiled at level 2, but sometimes the order of execution may seem strange.

Optimization makes your program smaller and faster. In most cases it also makes the generated code easier to understand. So think of the option -O2 as the norm, and only use other levels of optimization when you want to get something special.

The extent to which optimization makes a whole program smaller and faster depends on many things. In the case of hello.c there will be little benefit since most of the code in the executable file is in the library functions, and these are already optimized.

The following example is more representative and shows the Whetstone benchmark program reduced to 60% of its size, and running 76% faster. You can find Whetstone in the CD-ROM directory /mnt/cdrom/benchmarks/.

Here are the results when compiling with no optimization.

$ m1750-coff-gcc -c -O0 whetstone.c
$ m1750-coff-size whetstone.o
text    data    bss     dec     hex     filename
4566    0       12      4578    11e2    whetstone.o
$ m1750-coff-gcc -O0 whetstone.c -o whetstone
$ m1750-coff-run whetstone
,.,. whetstone GTS Version 0.1
---- whetstone Whetstone scientific benchmark.
   - whetstone Rating = 757 KWIPS.
==== whetstone  PASSED ============================.

Here are the results when compiling with optimization level 2.

$ m1750-coff-gcc -c -O2 whetstone.c
$ m1750-coff-size whetstone.o
text    data    bss     dec     hex     filename
2768    0       12      2780    adc     whetstone.o
$ m1750-coff-gcc -O2 whetstone.c -o whetstone
$ m1750-coff-run whetstone
,.,. whetstone GTS Version 0.1
---- whetstone Whetstone scientific benchmark.
   - whetstone Rating = 1234 KWIPS.
==== whetstone  PASSED ============================.

At optimization level 3, the compiler will automatically in-line calls of small functions. This may increase the size of the generated code, and the code will run faster. However the code motion due to inlining may make the generated code difficult to read and debug.

$ m1750-coff-gcc -c -O3 whetstone.c
$ m1750-coff-size whetstone.o
text    data    bss     dec     hex     filename
2768    0       12      2780    adc     whetstone.o
$ m1750-coff-gcc -O3 whetstone.c -o whetstone
$ m1750-coff-run whetstone
,.,. whetstone GTS Version 0.1
---- whetstone Whetstone scientific benchmark.
   - whetstone Rating = 1492 KWIPS.
==== whetstone  PASSED ============================.

You can find Whetstone and other benchmarks in the CD-ROM directory /mnt/cdrom/benchmarks/.