600-Level Challenge: The Optimization Pass

NemiLabs has a file transfer utility.

It works. It reports progress, displays an estimated time remaining, and even draws a progress bar.

Unfortunately, nobody seems to have spent much time making it efficient.

That's your job.

In this challenge, you'll take a working program and optimize it using the techniques from the 600-level.

Unlike our previous challenges, you won't need to build the entire program yourself. Most of the work has already been done.

Your task is to make it faster without changing what it does.

The Transfer

Our utility simulates transferring 1,000 files.

We're not actually reading or writing anything to disk. Instead, each fictional file requires a small amount of computational work.

For every file, the program runs a loop that counts from 0 to 100.

Once that work is complete, the file is considered transferred.

The utility keeps track of:

  • The total number of files.
  • How many files have been transferred.
  • How many remain.
  • The percentage completed.
  • The estimated time remaining.

It also draws a progress bar and updates the display periodically.

For 1,000 files, the display updates every 10 files, or approximately once per percentage point.

The update interval is calculated from the total, with a minimum of 10 files between regular updates. A final update ensures the display reaches 100%, even if the total isn't evenly divisible by the interval.

A Thousand Small Files

Transferring 1,000 files of 1 KB each might sound equivalent to transferring one file of roughly 1 MB.

After all, the total amount of data is nearly identical.

But historically, transferring many small files could be dramatically slower.

Each file comes with its own overhead. The system may need to locate it, open it, read its metadata, transfer its contents, create a destination entry, and close it again.

On mechanical hard drives and floppy disks, locating scattered files could require physically moving the read/write head. Network transfers might also require additional requests and acknowledgements for each file.

A single large file can often be transferred as a continuous stream, avoiding much of that repeated work.

This is one reason archive formats such as TAR became useful. Originally developed for magnetic tape, TAR combines many files into one continuous archive.

It also helps explain a familiar experience: a transfer reaches 99%, then appears to stop progressing.

Perhaps most of the bytes have already been transferred, but thousands of tiny files still need to be processed.

The amount of data remaining isn't necessarily proportional to the amount of work remaining.

Our simulated transfer deliberately gives every file the same workload, making its progress easier to estimate.

The Starter Program

Here's the utility in its original form.

-- NemiLabs File Transfer Utility
-- Unoptimized edition

#total $000
#done $001
#remaining $002
#percent $003
#interval $004
#until_update $005
#work $006

#lap $007
#elapsed $008
#eta $009
#bar_length $00A
#bar $00B

MOVE #total 1000
MOVE #done 0
MOVE #elapsed 0

DIV #interval #total 100
MAX #interval #interval 10
MOVE #until_update #interval

-- Start measuring.
TIMER #lap

:next_file
MOVE #work 0

:transfer
INC #work
BLT :transfer #work 100

INC #done
DEC #until_update

BLE :update #until_update 0
BLT :next_file #done #total
JUMP :update

:update
TIMER #lap
ADD #elapsed #elapsed #lap

SUB #remaining #total #done
MUL #percent #done 100
DIV #percent #percent #total

-- Estimate remaining milliseconds.
MUL #eta #elapsed #remaining
DIV #eta #eta #done

-- Convert to seconds.
DIV #eta #eta 1000

-- Build a 20-character progress bar.
DIV #bar_length #percent 5
S.PADR #bar "" "#" #bar_length
S.PADR #bar #bar "." 20

-- Draw the progress display.
D.FIL ""
D.CUR 0 0
D.TXT "NemiLabs File Transfer\r\n"
D.TXT "\r\n"
D.TXT "["
D.TXT #bar
D.TXT "] "
D.TXT #percent
D.TXT "%\r\n"
D.TXT "\r\n"
D.TXT "Completed: "
D.TXT #done
D.TXT " / "
D.TXT #total
D.TXT "\r\n"
D.TXT "Remaining: "
D.TXT #remaining
D.TXT "\r\n"
D.TXT "ETA: "
D.TXT #eta
D.TXT " seconds"
D.BLT

-- Continue until every file is transferred.
MOVE #until_update #interval
BLT :next_file #done #total

HALT

Run the program before making any changes.

Watch the progress bar, the file counter, and the estimated time remaining.

Notice how the ETA behaves during the first few updates.

The estimate is calculated by dividing the elapsed time by the number of completed files to find the average time per file, then multiplying that average by the number of files remaining.

The program measures elapsed time in milliseconds, then converts the result to seconds for display.

At the beginning, even small variations in execution time can produce large changes in the estimate. As more files are completed, the average generally becomes more representative.

That's one reason real file transfer utilities can be so spectacularly bad at estimating how much time remains when they've only just started.

Your Assignment

Optimize the program while preserving its behavior.

Your improved version must still:

  1. Simulate exactly 100 units of work for each file.
  2. Transfer the configured number of files.
  3. Calculate the completed count, remaining count, percentage, and ETA.
  4. Update the display at the same intervals.
  5. Produce a final display showing 100% completion.

You may reorganize instructions, combine them into source lines, change the control flow, and use non-blocking operations.

You should not remove the simulated work or reduce the number of progress updates merely to make the program finish sooner.

The goal is to perform the same job more efficiently.

Finding Opportunities

Before changing anything, read through the program and identify where execution time is likely being spent.

Consider the inner transfer loop. It executes 100 times for every file.

How many source fetches does that require?

Could the CPU repeat those instructions without fetching them again?

Now look at the rest of the program.

Some instructions execute only once, while others execute hundreds or thousands of times.

Which sections would benefit most from coalescing?

Finally, consider the display.

Does the CPU need to wait for the entire refresh to finish before beginning the next transfer?

Or could useful work happen while the display is busy?

Be Careful With Control Flow

Coalescing instructions can reduce source fetches, but it also changes how instructions are grouped into program lines.

Remember that branches target entire source lines, not individual instructions within them.

A label on a coalesced line identifies the beginning of that line.

Also remember that a taken branch immediately ends execution of the current source line.

For example:

JUMP :finished; INC #done

The INC instruction will never execute.

Similarly:

BLT :next_file #done #total; HALT

The HALT executes only when the branch is not taken.

That might be exactly what you want.

Or it might introduce a bug.

Don't coalesce instructions simply because they're adjacent. Think about how execution reaches and leaves each line.

Measuring Your Improvement

A program that looks more efficient isn't necessarily faster.

Use TIMER to measure the elapsed time.

You can measure the complete transfer, individual sections, or both.

Remember that TIMER resets whenever it's read, so measuring the total duration across multiple progress updates requires accumulating the elapsed intervals.

Run the original program several times and record the results.

Then run your optimized version.

Do you see a consistent improvement?

Try changing #total to another value, such as 250 or 1007.

Does the program still terminate correctly?

Does the final progress update show 100%?

Does the estimated time remaining reach zero?

Stuck?

The hints below offer progressively more specific suggestions.

Try solving each part yourself before opening the corresponding example.

How do I make the inner loop?

Look at these instructions:

:transfer
INC #work
BLT :transfer #work 100

The CPU repeatedly executes the same two instructions.

In NCL 603, we learned how to keep a loop entirely within one cached source line.

Can you apply that technique here?

Still stuck?

Replace the inner loop with:

INC #work; BLT @0 #work 100

Both instructions now occupy the same source line.

@0 branches to the beginning of the current line, allowing the CPU to repeat the instructions without fetching them again.

The loop still executes 100 times for each file.

What should I be coalescing?

The progress calculations contain several instructions that execute sequentially.

For example:

SUB #remaining #total #done
MUL #percent #done 100
DIV #percent #percent #total

These instructions have no branch destinations between them.

They can safely share a source line.

Look for similar opportunities elsewhere.

Be more cautious around labels, conditional branches, JUMP, and HALT.

Still stuck?

The calculations can be coalesced like this:

SUB #remaining #total #done; MUL #percent #done 100; DIV #percent #percent #total

The ETA calculations are another candidate:

MUL #eta #elapsed #remaining; DIV #eta #eta #done; DIV #eta #eta 1000

These instructions execute in sequence, with no branches entering or leaving partway through the line.

You can also combine many of the display commands.

However, avoid joining an instruction to a preceding line if that instruction must remain a separate branch destination.

How do I manage the display?

The starter program uses:

D.BLT

This waits for the display refresh to finish.

What happens if you replace it with D.BLTN?

The CPU can resume before the display finishes rendering.

However, the next display command will still need to wait if the display is busy.

Look at the instructions following the refresh. The next several files can be transferred without touching the display.

That's useful work the CPU can perform while the previous frame is being rendered.

Still stuck?

The simplest change is:

D.BLTN

Instead of waiting for the refresh to finish, the CPU can continue to:

MOVE #until_update #interval
BLT :next_file #done #total

It then begins transferring more files.

No additional display commands are issued until the next progress update.

This gives the display time to finish rendering while the CPU performs useful work.

Notice that D.BLTN doesn't make the refresh itself faster. It allows other work to happen during the refresh.

Where should I put my labels and branches?

Consider this section:

BLE :update #until_update 0
BLT :next_file #done #total
JUMP :update

The first branch enters the update routine when the interval expires.

The second branch skips the update if more files remain.

The final jump ensures that a completed transfer receives its final update.

You can coalesce these instructions, but each taken branch must still behave as intended.

Also examine the instructions following :update.

Which lines need to remain valid entry points?

Still stuck?

The three branches can share a source line:

BLE :update #until_update 0; BLT :next_file #done #total; JUMP :update

If the first branch is taken, execution immediately jumps to :update.

Otherwise, the CPU evaluates the second branch.

If neither condition is satisfied, the final JUMP executes.

The behavior is unchanged.

But be careful when coalescing instructions around labels.

For example, :update must still identify the beginning of the update routine's source line.

If you place it after unrelated instructions on the same line, branching to it will execute those instructions first.

Show me one solution

There are several ways to improve the program.

Here's one possible version.

-- NemiLabs File Transfer Utility
-- Optimized edition

#total $000
#done $001
#remaining $002
#percent $003
#interval $004
#until_update $005
#work $006

#lap $007
#elapsed $008
#eta $009
#bar_length $00A
#bar $00B

MOVE #total 1000
MOVE #done 0; MOVE #elapsed 0

DIV #interval #total 100; MAX #interval #interval 10
MOVE #until_update #interval

TIMER #lap

:next_file
MOVE #work 0

INC #work; BLT @0 #work 100

INC #done; DEC #until_update
BLE :update #until_update 0; BLT :next_file #done #total; JUMP :update

:update
TIMER #lap; ADD #elapsed #elapsed #lap

SUB #remaining #total #done; MUL #percent #done 100; DIV #percent #percent #total

MUL #eta #elapsed #remaining; DIV #eta #eta #done; DIV #eta #eta 1000

DIV #bar_length #percent 5
S.PADR #bar "" "#" #bar_length; S.PADR #bar #bar "." 20

D.FIL ""; D.CUR 0 0
D.TXT "NemiLabs File Transfer\r\n\r\n"
D.TXT "["; D.TXT #bar; D.TXT "] "; D.TXT #percent; D.TXT "%\r\n\r\n"
D.TXT "Completed: "; D.TXT #done; D.TXT " / "; D.TXT #total; D.TXT "\r\n"
D.TXT "Remaining: "; D.TXT #remaining; D.TXT "\r\n"
D.TXT "ETA: "; D.TXT #eta; D.TXT " seconds"
D.BLTN

MOVE #until_update #interval
BLT :next_file #done #total

HALT

The inner transfer loop now repeats from a cached source line.

Sequential calculations and display commands have been coalesced to reduce source fetching.

Branch destinations remain accessible, and taken branches still end execution of their source lines.

Finally, D.BLTN allows the next batch of simulated transfers to begin while the previous display refresh is underway.

The program still performs the same work and updates the display at the same intervals.


Ready to continue? In the next lesson, NCL 701: State and Presentation, we'll begin exploring how complete applications organize their behavior and interfaces around different states.