NCL 606: Measuring Time

Throughout the 600-level, we've been examining what makes programs faster or slower.

We've learned that fetching instructions has a cost, that some operations require more processing than others, and that the CPU can sometimes continue working while a peripheral is busy.

But so far, we've mostly discussed these costs without measuring them.

How can we tell whether one implementation is actually faster than another?

For that, we need to measure time.

The NCS/e provides three CPU instructions for working with time:

  • TIME retrieves the current Unix time.
  • TIMESTAMP retrieves the current date and time as a string.
  • TIMER measures how much time has elapsed.

All three execute internally on the CPU, without requiring a request to the kernel or an external component.

Unix Time

Computers frequently need to record when something happened.

A program might need to remember when a file was created, when a message arrived, or when a particular event occurred.

One common way to represent time is Unix time.

Unix time counts the number of seconds elapsed since January 1, 1970, at midnight UTC.

That starting point is called the Unix epoch.

Rather than storing a year, month, day, hour, minute, and second separately, Unix time represents a moment using a single integer.

NCL provides the TIME instruction:

TIME $000

This stores the current Unix timestamp in $000.

For example, the value might be:

1749990896

The important thing isn't the particular number. It's that every second increases the timestamp by one.

This makes it convenient for calculations.

Suppose we want to determine how many seconds have passed between two events.

#start $000
#end $001
#elapsed $002

TIME #start

-- Perform some work.

TIME #end

SUB #elapsed #end #start

The result is the number of seconds between the two readings.

This is useful for measuring longer intervals, but there's a limitation.

TIME only measures whole seconds.

An operation taking 50 milliseconds and another taking 500 milliseconds might produce exactly the same result.

To measure short operations, we'll need something more precise.

Unix Time and the Year 2038

Unix time originated with the Unix operating system, developed at Bell Labs beginning in 1969.

Counting seconds from a fixed starting point made time convenient to store and manipulate using integers.

However, the NCS/e uses signed 32-bit integers.

The largest positive value such an integer can represent is 2,147,483,647.

As a Unix timestamp, that corresponds to January 19, 2038, at 03:14:07 UTC.

One second later, the timestamp exceeds the positive range of a signed 32-bit integer.

This is known as the Year 2038 problem.

Modern systems can avoid it by using wider integer representations, but the NCS/e retains its 32-bit architecture.

Fortunately, we still have a few years before the accountants need to worry about that.

Coordinated Universal Time

You may have noticed that Unix time uses UTC.

UTC is the internationally agreed abbreviation for Coordinated Universal Time.

The abbreviation doesn't match the English word order because it was chosen as a compromise between the English and French names.

Unlike local time, UTC doesn't change according to geographical location or daylight saving time.

For example, when it's 14:00 UTC, it might be morning in North America and evening in Europe.

But the UTC time itself is the same everywhere.

This is particularly useful for computers communicating across different locations.

If two programs record an event using UTC, they don't need to know each other's local time zones to compare those timestamps.

The NCS/e's time instructions use UTC.

Reading a Timestamp

Unix time is convenient for calculations, but it isn't particularly pleasant to read.

If we want to display the current date and time, we could convert the Unix timestamp into a calendar date ourselves.

That would require accounting for years, leap years, months, and the different numbers of days in each month.

Fortunately, the CPU can provide the formatted date and time directly.

TIMESTAMP $000

Unlike TIME, TIMESTAMP stores a string.

For example:

2025-06-15T12:34:56.123456Z

This follows the ISO 8601 date and time format.

Component Value Meaning
Year 2025 Calendar year
Month 06 June
Day 15 Day of the month
Hour 12 Hour, using a 24-hour clock
Minute 34 Minute
Second 56 Second
Fraction 123456 Fractional seconds
Z — UTC time

The T separates the date from the time.

The Z at the end indicates that the timestamp uses UTC.

Notice that the fractional seconds provide finer resolution than TIME, including milliseconds.

Extracting Date and Time

One particularly useful property of this format is that its components occupy fixed positions.

We don't need a special instruction to retrieve the current date.

We can simply extract it from the timestamp using S.SUB.

#timestamp $000
#date $001
#time $002

TIMESTAMP #timestamp

S.SUB #date #timestamp 0 9
S.SUB #time #timestamp 11 18

For our example timestamp:

2025-06-15T12:34:56.123456Z

The results are:

#date = "2025-06-15"
#time = "12:34:56"

Remember that S.SUB uses inclusive start and end positions.

We can extract individual components just as easily.

Component Start End
Year 0 3
Month 5 6
Day 8 9
Hour 11 12
Minute 14 15
Second 17 18
Milliseconds 20 22

This means TIMESTAMP can provide the current date, time, and individual calendar components without requiring separate instructions for each one.

Formatting versus calculating

TIMESTAMP is useful when we want to know the current date and time.

It doesn't convert arbitrary Unix timestamps into calendar dates, calculate weekdays, or perform calendar arithmetic.

Those are separate problems.

Measuring Elapsed Time

Now let's return to our original problem.

We want to measure how long an operation takes.

TIME only provides whole seconds, and extracting milliseconds from TIMESTAMP would require additional string operations and handling the clock crossing midnight.

Instead, the CPU provides a dedicated stopwatch:

TIMER $000

TIMER performs two actions:

  1. Retrieves the number of milliseconds elapsed since the timer was last reset.
  2. Immediately resets the timer to begin measuring the next interval.

The result is stored as an integer.

Whenever a new NCL program starts, its timer is reset automatically.

That means the first TIMER instruction measures the time elapsed since the program began executing.

Every subsequent TIMER measures the time since the previous TIMER instruction.

Measuring Startup Time

Suppose our program performs some initialization before displaying its first screen.

#elapsed $000

-- Initialize the display.
D.FIL ""
D.CUR 0 0
D.TXT "Initializing..."
D.BLT

TIMER #elapsed

At this point, #elapsed contains the number of milliseconds since the program started.

We didn't need to start the timer ourselves.

The CPU did that when the program was invoked.

Measuring an Operation

What if we only want to measure a particular section of code?

We can call TIMER twice.

#elapsed $000

TIMER #elapsed

-- Perform the operation being measured.

TIMER #elapsed

The first call resets the timer.

We don't care about its returned value.

The second call retrieves the elapsed time and resets the timer again.

For example, if the measured operation takes 125 milliseconds, the second TIMER stores:

125

We can immediately use that result in calculations or display it.

There are no separate instructions for starting, stopping, or resetting the stopwatch.

Reading the timer always resets it.

One stopwatch

The CPU maintains one elapsed-time timer for the executing program.

Every TIMER instruction resets that same timer.

If a subroutine calls TIMER, it also resets the interval being measured by its caller.

When benchmarking, make sure nothing else calls TIMER between your two measurements.

Our First Benchmark

In NCL 603: Hot Loops, we learned how to repeat instructions from a cached source line without fetching that line again.

We can now measure the difference.

First, let's write an ordinary loop.

#elapsed $000
#counter $001

MOVE #counter 0

TIMER #elapsed

:loop
INC #counter
BLT :loop #counter 1000

TIMER #elapsed

D.TXT "Ordinary loop: "
D.TXT #elapsed
D.TXT " ms"
D.BLT

This increments a counter one thousand times.

Each iteration branches back to :loop, requiring the CPU to fetch the source again.

The final TIMER records how long the loop took.

Now let's try the same calculation using a hot loop.

#elapsed $000
#counter $001

MOVE #counter 0

TIMER #elapsed

INC #counter; BLT @0 #counter 1000

TIMER #elapsed

D.TXT "Hot loop: "
D.TXT #elapsed
D.TXT " ms"
D.BLT

Both programs perform the same calculation.

Both increment the counter from zero to one thousand.

But the second program repeats instructions already present in the CPU's cached source line.

It doesn't need to fetch the loop body again on every iteration.

Try running both programs.

Which one finishes faster?

How large is the difference?

Does that difference remain consistent across multiple runs?

Understanding the Results

You may notice something interesting when running the benchmarks.

The same program doesn't always take exactly the same amount of time.

One run might report a slightly different result from the next.

That's normal.

The NCS/e doesn't execute in a perfectly isolated environment.

The CPU must share execution time with other activity, and scheduling delays can affect how quickly instructions are processed.

Even the timing instructions themselves require a small amount of processing.

This means a benchmark measures the total elapsed time between two readings, not just the processing time of an individual instruction.

There are several ways to make our measurements more useful.

Measure Enough Work

Suppose an operation takes only a tiny fraction of a millisecond.

Measuring it once might produce a result of zero milliseconds.

That doesn't mean the operation took no time.

It means the elapsed time was too small to distinguish using our integer millisecond measurement.

Instead, we can repeat the operation many times and measure the total.

That's why our example uses a thousand iterations rather than measuring a single INC.

Repeat Your Measurements

Run the same benchmark several times.

If one run is unusually fast or slow, don't immediately assume the program changed its behavior.

Look for a consistent difference between the implementations.

A single measurement is useful, but repeated measurements give us a better understanding of typical performance.

Compare Equivalent Work

A benchmark is only meaningful if the implementations perform equivalent tasks.

Our ordinary loop and hot loop both increment the same counter the same number of times.

The difference lies in how the instructions are executed.

If one program performs fewer calculations, produces less output, or skips part of the work, we aren't making a fair comparison.

Measuring the Right Thing

In NCL 605: Non-Blocking Operations, we learned that D.BLT waits for the display refresh to finish, while D.BLTN acknowledges the request before rendering is complete.

Consider these two measurements:

TIMER #elapsed
D.BLT
TIMER #elapsed
TIMER #elapsed
D.BLTN
TIMER #elapsed

The second measurement will generally be much shorter, assuming the display is initially available.

But D.BLTN doesn't render the display faster.

It simply returns control to the CPU earlier.

A benchmark only tells us how long the measured interval took. We still need to understand what happened during that interval.

Try It

Return to the ordinary loop and hot loop from earlier.

Run each benchmark several times and record the results.

Then experiment with the iteration count.

Try:

  • 100 iterations.
  • 1,000 iterations.
  • 10,000 iterations.

Does the difference become more noticeable as the number of iterations increases?

Do the results scale proportionally with the iteration count?

Next, try measuring another operation you've encountered during the course.

For example, compare two ways of constructing the same string or performing the same calculation.

Make sure both implementations produce equivalent results.

Benchmarking small operations

If the elapsed time is consistently zero, the operation may be too short to measure individually.

Try repeating it in a loop.

Remember that the loop itself has a cost, so your measurement includes both the operation and the instructions controlling the loop.

For very small operations, that overhead may be a significant part of the result.

Comparing loop overhead

One way to estimate how much time your loop machinery consumes is to benchmark a loop that performs very little work.

Then compare it with a loop that performs the operation you're interested in.

The difference can provide a rough estimate of the operation's cost.

It won't be perfectly precise, but it can help you understand where the execution time is going.


We can now put numbers to the performance techniques we've learned throughout this level.

Instead of guessing which implementation is faster, we can measure it, compare the results, and decide whether an optimization is worthwhile.

Want to put these techniques into practice? The optional 600-Level Challenge will ask you to optimize a working program and measure the improvement.

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.