395 | | |
396 | | |
397 | | |
| 395 | ==== How to Optimize ==== |
| 396 | * Loop Ordering: Nested loops should be ordered with the simplest loop outermost and the most complex loops innermost |
| 397 | * Powers of 2: Use a power of 2 when doing integer multiply or divide. Most compilers substitute a shift for the operation. |
| 398 | * Pointers: Using pointers is faster than indexing an array. |
| 399 | * 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. |
| 400 | * Reduction in strength: Use cheap operations, there's a table of cost of common operations: |
| 401 | || '''Operation''' || '''Relative cost''' || |
| 402 | || printf and scanf || 1000 || |
| 403 | || malloc and free || 800 || |
| 404 | || trigonometric functions (sin, cos...) || 500 || |
| 405 | || floating point (any operation) || 100 || |
| 406 | || integer divide || 30 || |
| 407 | || integer multiple || 20 || |
| 408 | || function call || 10 || |
| 409 | || simple array index || 6 || |
| 410 | || shifts || 5 || |
| 411 | || add/substract || 5 || |
| 412 | || pointer dereference || 2 || |
| 413 | || bitwise and, or, not || 1 || |
| 414 | || logical and, or, not || 1 || |