NCL 603: Hot Loops

In the previous lesson, we learned how to coalesce instructions to reduce the number of line fetches.

But there's an especially useful case we haven't explored yet.

What if we could execute the same line repeatedly without fetching it again?

On the NCS/e, we can.

Repeating a Line

Consider a simple loop:

#counter $000

MOVE #counter 0

:loop
INC #counter; BLT :loop #counter 100

This increments #counter until it reaches 100.

We've already coalesced the two instructions inside the loop, so each iteration requires only one executable line.

However, the CPU still needs to fetch that line on every iteration.

Why?

Because the branch target, :loop, refers to the preceding source line.

Even though the kernel skips the label-only line and returns the following executable line, the CPU sees the branch as a transfer to a different program line.

Now consider a small change:

#counter $000

MOVE #counter 0

:loop; INC #counter; BLT :loop #counter 100

We've moved the label onto the executable line, separating it from the instructions with a semicolon.

The program behaves exactly as before.

But now, when BLT branches to :loop, its destination is the same source line the CPU is already executing.

The CPU can repeat the instructions it has already fetched.

This is a hot loop.

How Hot Looping Works

Normally, a branch changes the program counter (pc) and ends execution of the current line.

The CPU then needs to fetch the line identified by the new program counter.

But there's a special case.

If a branch sets pc to the exact same program line that's currently executing, the CPU can reuse the line it already has.

Instead of requesting it from the kernel, the CPU starts executing that line again from its first instruction.

This continues until execution leaves the line.

The distinction is important:

Ordinary loop Hot loop
Label Previous source line Same source line
Branch destination Different line Current line
Fetch on each iteration Yes No
Reuses fetched instructions No Yes

Both loops perform the same calculations and evaluate the same branch.

The hot loop simply avoids repeated line fetches.

A Convenient Shortcut: @0

We've previously used relative branch targets such as @1 and @-1.

There's another particularly useful relative target:

@0

This refers to the current source line.

So instead of writing:

:loop; INC #counter; BLT :loop #counter 100

We can write:

INC #counter; BLT @0 #counter 100

The behavior is identical.

Since @0 refers to the current line, the branch keeps the loop hot without requiring a label.

This is especially convenient when a label exists only to make the loop repeat.

Of course, a same-line label is still useful when another part of the program needs to enter the loop by name.

An Ideal Hot Loop

Let's put this into practice.

Suppose we want to calculate the sum of the integers from 1 to 100.

We can initialize our values on one line, then perform the entire calculation on another:

#counter $000
#total $001

-- Initialize the counter and accumulator.
MOVE #counter 100; MOVE #total 0

-- Sum the integers from 100 down to 1.
ADD #total #total #counter; DEC #counter; BGT @0 #counter 0

The first executable line initializes our two values.

The second line:

  1. Adds the current counter to the total.
  2. Decrements the counter.
  3. Branches back to itself while the counter is greater than zero.

After 100 iterations, #counter contains 0 and #total contains 5050.

And despite executing the loop 100 times, the CPU only needs to fetch two executable lines for the entire program.

One for initialization, and one for the loop.

The loop also requires 99 internal restarts, rather than 99 additional line fetches.

Notice that the setup isn't included in the hot loop. It only needs to execute once, so there's no reason to repeat it.

This is a useful general pattern: initialize your values, then keep the repeated work together on one line.

The Performance Difference

Let's revisit the illustrative communication cost from 601.

Assume a line fetch takes 10 ms.

Hot looping avoids that communication, but restarting a cached line still involves a small amount of internal scheduling.

For our examples, we'll assume that takes 1 ms.

About Performance Estimates

The timings used throughout this course are illustrative.

Actual performance depends on system load, scheduling overhead, and the instructions being executed.

Imagine a loop that performs ten arithmetic instructions per iteration, repeated 100 times.

We can organize it in three ways:

  • Separate lines: Ten executable lines, fetched on every iteration.
  • Coalesced: All ten instructions on one line, but the loop branches to a different source line.
  • Hot loop: All ten instructions on one line, with the branch returning to that same line.
Separate lines Coalesced Hot loop
Iterations 100 100 100
Arithmetic instructions 1,000 1,000 1,000
Line fetches 1,000 100 1
Internal loop restarts 0 0 99
Fetch overhead 10.00 s 1.00 s 0.01 s
Internal scheduling overhead — — 0.099 s
Total estimated overhead 10.00 s 1.00 s 0.109 s

Coalescing alone reduces the estimated overhead from ten seconds to one.

Hot looping brings it down to approximately 109 milliseconds.

That's roughly 92 times less overhead than the original ten-line loop, and about nine times less than ordinary coalescing.

The hot loop still has to restart internally between iterations, but that's considerably cheaper than asking the kernel to fetch the same line again.

Of course, these figures don't include the time spent executing the arithmetic instructions themselves.

The CPU still performs every calculation.

But simple arithmetic is comparatively fast, so eliminating repeated fetches can make an enormous difference.

Loop Mode

The Motorola 68010, introduced in 1982, featured an optimization called Loop Mode.

When executing certain two-instruction loops, the processor could retain the instructions it had already fetched and repeat them without fetching their opcodes from memory again.

The NCS/e uses a similar idea, but operates on entire source lines rather than individual machine instructions.

In both cases, the advantage is the same: repeatedly executing instructions already available to the processor is faster than repeatedly requesting them.

Hot Loops with Coprocessors

Hot looping isn't limited to arithmetic.

A loop can also contain instructions that communicate with coprocessors.

For example:

#counter $000
#text $001

MOVE #counter 0; MOVE #text ""

S.JOIN #text #text "A"; INC #counter; BLT @0 #counter 100

This appends "A" to a string 100 times.

The loop is hot because its branch returns to the currently executing line.

When S.JOIN communicates with the string coprocessor, the CPU waits for its response.

Once the response arrives, execution continues within the same fetched line.

If the final branch returns to that line, the CPU can repeat it without fetching it again.

However, S.JOIN still needs to communicate with the string coprocessor on every iteration.

Hot looping eliminates repeated line fetches, not communication performed by the instructions themselves.

Let's compare four hypothetical loops, each performing ten operations per iteration for 100 iterations.

We'll use our illustrative 10 ms communication round trip, 1 ms internal loop restart, and assume each string operation requires one coprocessor call.

Loop Line fetches Coprocessor calls Internal restarts Estimated overhead
Ten-line arithmetic loop 1,000 0 0 10.000 s
Hot arithmetic loop 1 0 99 0.109 s
Ten-line string loop 1,000 1,000 0 20.000 s
Hot string loop 1 1,000 99 10.109 s

The arithmetic hot loop benefits enormously because its operations execute locally.

The string hot loop still needs 1,000 coprocessor calls, but it eliminates almost all its line-fetch overhead.

Even though it cannot avoid communicating with the coprocessor, it saves nearly half the estimated overhead.

So don't dismiss hot looping just because a loop contains coprocessor operations.

Every avoided line fetch is one less request the CPU has to wait for.

The Limits of Hot Looping

Hot loops are powerful, but not every loop can be made hot.

Multiple Entry Points

Remember that a branch target always identifies an entire source line.

It cannot enter halfway through a coalesced line.

If a loop needs to branch between different points within its own body, those points must occupy separate executable lines.

For example:

:loop
BEQ :skip $000 0
ADD $001 $001 $000

:skip
DEC $000
BGT :loop $000 -10

This loop has two distinct entry points: :loop and :skip.

We can't simply coalesce the entire loop into one line, because :skip needs to enter after the ADD.

And since those entry points require different source lines, the CPU cannot execute the entire loop as a single hot line.

Some loops genuinely require more complicated control flow.

That's perfectly fine.

Branches Always End the Line

A branch that writes to pc immediately ends execution of the current line.

This is true even when the new program counter points to the line that would naturally execute next.

For example:

INC $000; JUMP @1; INC $001

The second INC is unreachable.

The JUMP explicitly changes pc, so execution leaves the current line.

A hot loop works because the CPU recognizes that the new pc identifies the line it already has, not because the branch somehow avoids ending the line.

When the branch is taken, the current execution pass ends and the line restarts from its first instruction.

When the branch isn't taken, execution continues normally.

When to Use Hot Loops

Hot looping is particularly valuable when a short sequence of instructions executes many times.

Arithmetic-heavy loops can benefit tremendously, but loops containing coprocessor operations are also worthwhile candidates.

Still, there's no need to force every loop into a single line.

If a loop requires several entry points, splitting it across lines may be unavoidable. And making a complicated program difficult to understand just to save a few fetches isn't always a worthwhile trade.

A good approach is to:

  • Keep initialization outside the repeated work.
  • Coalesce instructions that naturally execute together.
  • Use @0 when a loop only needs to branch back to itself.
  • Keep a same-line label when the loop needs a named entry point.
  • Preserve readable code when the control flow requires multiple lines.

The goal isn't to make every loop hot.

It's to recognize when a loop can be hot, and take advantage of it when doing so is useful.

What's Next?

We've seen that the time spent fetching instructions can greatly exceed the time spent executing simple arithmetic.

And we've learned how to eliminate most of that overhead using coalescing and hot loops.

But even when communication is unavoidable, not every operation takes the same amount of time.

Some instructions perform very little work. Others perform considerably more.

In NCL 604: The Cost of an Operation, we'll look at what happens after an instruction has been fetched, and why different operations can have very different execution costs.