2.2. Using Optimizations

Optimization makes your program smaller and faster. In most cases it also makes the generated code easier to understand. The default level of optimization is level 2. If you need to remove all optional optimization then use level 0. 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.

$ erc-coff-gcc -c -O0 whetstone.c
$ erc-coff-size whetstone.o
   text    data     bss     dec     hex filename
   7904       0      12    7916    1eec whetstone.o
$ erc-coff-gcc -O0 whetstone.c -o whetstone
$ erc-coff-run whetstone
,.,. whetstone GTS Version 0.1
---- whetstone Whetstone scientific benchmark.
   - whetstone Rating = 4166 KWIPS.
==== whetstone  PASSED ============================.

Here are the results when compiling with optimization level 2.

$ erc-coff-gcc -c -O2 whetstone.c
$ erc-coff-size whetstone.o
   text    data     bss     dec     hex filename
   4500       0      12    4512    11a0 whetstone.o
$ erc-coff-gcc -O2 whetstone.c -o whetstone
$ erc-coff-run whetstone
,.,. whetstone GTS Version 0.1
---- whetstone Whetstone scientific benchmark.
   - whetstone Rating = 6666 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.

$ erc-coff-gcc -c -O3 whetstone.c
$ erc-coff-size whetstone.o
   text    data     bss     dec     hex filename
   4416       0      12    4428    114c whetstone.o
$ erc-coff-gcc -O3 whetstone.c -o whetstone
$ erc-coff-run whetstone
,.,. whetstone GTS Version 0.1
---- whetstone Whetstone scientific benchmark.
   - whetstone Rating = 7692 KWIPS.
==== whetstone  PASSED ============================.

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