Optimization basics

Measure first

Time the whole program before optimizing: clock_gettime around the hot loop, or the time command for a first look. Guessing at assembly performance is reliably wrong, so measure, fix one thing, measure again.

Memory is the cost

A register operation is one cycle; a cache hit is a few; a cache miss is hundreds. Most optimization is keeping data in registers and walking memory sequentially, because prefetch makes sequential access nearly free and random access expensive.

Fast patterns

Zero with XOR (xor eax, eax) instead of MOV, use LEA for address math and small multiplies, and unroll small loops when the body is shorter than the loop overhead. But the compiler in -O2 already knows these: beat it only after measuring.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is the first step of optimization?

    Answer

    Measure the program

    Without a measurement, a change may make the program slower and no one can tell.

  2. Which is usually the most expensive?

    Answer

    A cache miss

    A miss reaches memory and costs hundreds of cycles, while a register operation is one.

  3. Why is sequential memory access fast?

    Answer

    The prefetcher brings the next lines in advance

    A predictable stride lets the hardware fetch ahead, so the data is already in cache.

  4. Which instruction zeroes a register without reading memory?

    Answer

    xor eax, eax

    XOR of a register with itself is short and recognized by the CPU as a zeroing idiom.

  5. What is loop unrolling for?

    Answer

    To spend fewer instructions on the loop overhead

    Repeating the body inside one iteration removes some counter and branch instructions.

  6. What does LEA help with besides addresses?

    Answer

    Small multiplications and additions without touching flags

    The address unit computes base + index*scale + displacement, which is cheap arithmetic.

  7. Why can a compiler beat hand-written assembly on -O2?

    Answer

    It knows the target CPU and applies many transformations

    Modern compilers model the machine well, so hand assembly must be measured against them.

  8. What does time ./program show?

    Answer

    Real, user and system time of the run

    time reports the wall time and the CPU time the process used.

  9. Why is random memory access expensive?

    Answer

    Each new address can miss the cache and wait for memory

    The prefetcher cannot predict a random next address, so the data must be fetched on demand.

  10. What should you do after one optimization?

    Answer

    Measure again

    One change at a time shows which change helped and which one hurt.

Article author: Arthur Isaev