Download Practical C Programming - International Research Institute MICA

Transcript
262
Chapter 15: Debugging and Optimization
Reduction in strength
This phrase is a fancy way of saying you should use cheap operations instead
of expensive ones. Table 15-1 lists the relative cost of common operations.
Table 15-1: Relative Cost of Operations
Operation
Relative cost
printf and scanf
1000
malloc and free
800
trigonometric functions (sin, cos...)
500
floating point (any operation)
100
integer divide
30
integer multiple
20
function call
10
simple array index
6
shifts
5
add/subtract
5
pointer dereference
2
bitwise and, or, not
1
logical and, or, not
1
NOTE
Formatting functions like printf, scanf, and sscanf are extremely costly because they have to go through the format string one
character at a time, looking for a format conversion character (%).
Then they have to do a costly conversion between a character string
and a number. These functions should be avoided in time-critical
sections of code.
Powers of 2
Use a power of 2 when doing integer multiply or divide. Most compilers
substitute a shift for the operation.
Pointers
Using pointers is faster than indexing an array. Pointers are, however, more
tricky to use.
Macros
Using a macro eliminates the overhead associated with a function call. It also
makes the code bigger and a little more difficult to debug.