Chapter 7 of 1131 min read
How fast, and why
How aython's executables are timed against CPython, what the recorded ratios are, and which design choices make them what they are.
An aython program is a native executable with no interpreter in it, so it is tempting to assume it is fast. It is not automatically: every value is a boxed object, every assignment releases the old value with a call, and no call is ever inlined. This chapter shows how the executables are timed against CPython, how to read the ratios that come out, what the recorded numbers are, and which design choices make them what they are.
Speed was never the goal of the subset: the correctness rule comes first, and docs/bench-design.md says the harness exists “so the first optimization has something to move”. But a compiler that cannot say how fast its output runs, or why, is hiding something. The numbers below are the only timings on this site. They are wall-clock seconds recorded on native x86-64 Linux, on one machine; nothing here was timed under emulation, and nothing was timed for this page.
How a program is timed #
uv run aython bench takes each program in bench/programs/, builds it once with the judge’s build_program, and then times both sides in rounds. It does not compare output: bench-design.md requires a program to pass aython check before it is added, and the harness itself only requires each run to exit 0 (time_argv runs it with check=True).
src/aython/bench.py · bench_onelines 96–125def bench_one(source: Path, runtime_src: Path, repeat: int) -> BenchResult:
"""Time one program on both sides with alternating order.
Args:
source: Benchmark ``.py`` file (already differential-checked).
runtime_src: Path to ``runtime.s``.
repeat: Round count; even rounds run ELF first, odd CPython first.
Returns:
The per-round times plus best-of-N figures for both sides.
"""
from .judge import run_cpython, run_elf # local import: repo layout
elf_path = build_program(source, runtime_src)
result = BenchResult(name=source.name)
for i in range(repeat):
first, second = ("elf", "py") if i % 2 == 0 else ("py", "elf")
times: dict[str, float] = {}
for side in (first, second):
if side == "elf":
times["elf"] = time_argv([str(elf_path)], RUN_TIMEOUT_S)
else:
times["py"] = time_argv([CPYTHON_CMD, str(source)], RUN_TIMEOUT_S)
result.elf_times.append(times["elf"])
result.py_times.append(times["py"])
log.info("%s round %d/%d: elf %.3fs py %.3fs", source.name, i + 1, repeat, times["elf"], times["py"])
result.best_elf = min(result.elf_times)
result.best_py = min(result.py_times)
result.ratio = result.best_elf / result.best_py if result.best_py > 0 else float("inf")
return result
Each round runs the ELF and python3 <program> once each, as separate processes, timed with time.perf_counter around subprocess.run (time_argv). Three choices shape the result:
| Choice | What it does | What it protects against |
|---|---|---|
| Alternate the order | Even rounds run the ELF first, odd rounds CPython first | Slow drift (a warming CPU, a background job starting) always landing on the same side |
| Keep the best round | min over the rounds of each side |
Rounds where something else took the core; for a short program the minimum is the run with the least interference |
| Time the whole process | From fork/exec to exit, including loading and start-up |
Nothing; this is what a user waits for, and it is the reason small programs say little (below) |
The figure reported per program is the ratio of the two best times, ELF over CPython. Below 1 the ELF was faster; above 1 CPython was. 0.50x means the ELF took half as long, 2.00x twice as long. The report also lists every round, so a run whose rounds split into two clusters cannot hide behind its minimum.
The recorded numbers #
The results file is bench/results/sofeikov-mp-intel-r-core-tm-i5-14600kf.md, best of 7 rounds, on sofeikov-mp-intel-r-core-tm-i5-14600kf:
| Program | ELF best | CPython best | ELF / CPython |
|---|---|---|---|
dictbench.py |
0.001 s | 0.008 s | 0.07x |
fib20.py |
0.001 s | 0.009 s | 0.09x |
fib30.py |
0.076 s | 0.051 s | 1.48x |
listbuild.py |
0.001 s | 0.010 s | 0.09x |
strbuild.py |
0.001 s | 0.008 s | 0.17x |
sum10m.py |
0.327 s | 0.479 s | 0.68x |
sumloop.py |
0.004 s | 0.012 s | 0.31x |
7 programs in bench/programs/ have no row in that file: aliaschurn.py, callargs4.py, callnull.py, dictlookup.py, intsmall.py, listindex.py, rangefor.py. Each isolates one cost; their timings are recorded only in bench-design.md, in its optimisation sections and its table of discriminating programs.
Reading a ratio: three regimes #
bench-design.md names three regimes, and the recorded file shows all three.
Start-up dominated. CPython has to start an interpreter, set up its runtime and import its start-up modules before it runs the first line; the ELF starts at main with only crt and libc initialisation in front of it. A program that finishes in a few milliseconds measures that difference and almost nothing else. The smallest CPython time in the file is 0.008 s, and since every CPython round includes the start-up, that is an upper bound on what start-up costs on that machine. Ratios near 0.1x say only that the process starts quickly.
There is a second reason to distrust those rows: bench records three decimals, so an ELF best of 0.001 s means anywhere from half a millisecond to one and a half. A ratio computed from it can be off by a factor of three.
Flat native loops. sum10m.py runs ten million passes of total = total + i. The loop is a fixed sequence of helper calls with no dispatch between them, against CPython’s bytecode interpreter. The ELF wins, modestly, once start-up stops mattering.
Call-heavy code. fib30.py spends its time building and tearing down frames, adopting arguments and releasing locals. Every ownership transfer is an explicit call and no call is inlined or specialised, so this is where the ELF has the most per-operation overhead.
Separating start-up from work #
Each start-up-sized program has a scaled-up sibling running the same code: sumloop.py (100,000 passes) with sum10m.py (10,000,000), and fib20.py with fib30.py. If a program’s time is a fixed start-up cost plus a constant cost per unit of work, two sizes are enough to separate the two: the difference in time over the difference in work is the cost per unit, and what is left of the small program’s time is start-up. Applied to the recorded file:
| Pair | Unit of work | Side | Fitted start-up | Fitted cost per unit |
|---|---|---|---|---|
sumloop.py / sum10m.py |
one loop pass | ELF | 0.7 ms | 32.6 ns |
| CPython | 7.3 ms | 47.2 ns | ||
fib20.py / fib30.py |
one call of fib |
ELF | 0.4 ms | 28.1 ns |
| CPython | 8.7 ms | 15.7 ns |
fib(20) makes 21,891 calls and fib(30) makes 2,692,537 (each call of fib(n) with n of 2 or more makes two more), which is the unit for the second pair. Two points and one millisecond of resolution make this a rough reading, not a measurement, but it shows what the headline ratios hide. The ratio of the fitted per-unit costs, ELF over CPython, is 0.69 for the loop and 1.79 for the call. So the fib30.py ratio of 1.48x understates the per-call gap in that file: about 17% of CPython’s fib30.py time is start-up, which the ELF does not pay.
Where the time goes in one loop pass #
Speed questions are answered by reading the generated code. This is one pass of sum10m.py’s loop as the current frontend and codegen emit it, from the loop’s top label to its end label:
bench/programs/sum10m.py · emitted · .Lwhile_top_1.Lwhile_top_1: # every iteration starts here, reading current slots
mov rdi, [rbp-16] # borrow i directly (helper never consumes it; slot keeps ownership)
movabs rsi, 10000000 # raw bound in rsi: no box, no right-side cleanup
call obj_lt_imm # rax = immortal bool (or aborts TypeError, like the boxed form)
mov [rbp-24], rax # park the owned test value
mov rdi, [rbp-24] # arg = test value (helper borrows it)
call aython_not # rax = immortal (!test)
mov [rbp-32], rax # park the immortal negation (no decref: immortal)
# test value is immortal (comparison or `not`): no decref call
mov rax, [rbp-32] # reload (!test): calls clobbered rax AND flags
lea rcx, aython_false[rip] # rcx = immortal False address
cmp rax, rcx # !test == False means truthy; the jump reads these flags
jne .Lwhile_end_1 # falsy test exits the loop
# line 4: total = <expr> (release old, compute new, store)
mov rax, [rbp-8] # rax = total's object (still owned by the slot)
mov rdi, rax # arg = same pointer (helper borrows it)
call aython_incref # take our own shared ownership; rax = same pointer
mov [rbp-32], rax # park owned left operand (calls below would clobber rax)
mov rax, [rbp-16] # rax = i's object (still owned by the slot)
mov rdi, rax # arg = same pointer (helper borrows it)
call aython_incref # take our own shared ownership; rax = same pointer
mov [rbp-40], rax # park owned right operand
mov rdi, [rbp-32] # arg1 = left (helper borrows it)
mov rsi, [rbp-40] # arg2 = right (helper borrows it)
call int_add # rax = new owned result (or aborts TypeError/OverflowError/...)
mov [rbp-48], rax # park the result across the cleanup calls
mov rdi, [rbp-32] # release left operand
call aython_decref # (single-use temporaries usually freed here)
mov rdi, [rbp-40] # release right operand
call aython_decref # (same)
mov rax, [rbp-48] # rax = owned result for our caller
mov [rbp-24], rax # park the new owned value where calls cannot clobber it
mov rdi, [rbp-8] # rdi = old total (borrowed for the call)
call aython_decref # release old total; may free it right here
mov rax, [rbp-24] # rax = new value again (survived the call in memory)
mov [rbp-8], rax # total now owns the new value
# line 5: i = <expr> (release old, compute new, store)
mov rax, [rbp-16] # rax = i's object (still owned by the slot)
mov rdi, rax # arg = same pointer (helper borrows it)
call aython_incref # take our own shared ownership; rax = same pointer
mov [rbp-32], rax # park owned left operand (calls below would clobber rax)
# int literal: box it (movabs covers the full i64 range; small values hit the cache)
movabs rdi, 1 # arg = raw integer value (not a pointer yet)
call int_new # rax = new owned int box (refcnt 1)
mov [rbp-40], rax # park owned right operand
mov rdi, [rbp-32] # arg1 = left (helper borrows it)
mov rsi, [rbp-40] # arg2 = right (helper borrows it)
call int_add # rax = new owned result (or aborts TypeError/OverflowError/...)
mov [rbp-48], rax # park the result across the cleanup calls
mov rdi, [rbp-32] # release left operand
call aython_decref # (single-use temporaries usually freed here)
mov rdi, [rbp-40] # release right operand
call aython_decref # (same)
mov rax, [rbp-48] # rax = owned result for our caller
mov [rbp-24], rax # park the new owned value where calls cannot clobber it
mov rdi, [rbp-16] # rdi = old i (borrowed for the call)
call aython_decref # release old i; may free it right here
mov rax, [rbp-24] # rax = new value again (survived the call in memory)
mov [rbp-16], rax # i now owns the new value
jmp .Lwhile_top_1 # body ran; re-test with the updated slots
That is 14 calls per pass: aython_decref ×6, aython_incref ×3, int_add ×2, obj_lt_imm ×1, aython_not ×1, int_new ×1. They come from three rules the code generator applies everywhere, explained in the codegen chapter:
- A test produces an object.
i < 10000000returns the immortalTrueorFalse;aython_notnormalises it and the jump compares againstFalse’s address. Because both results are immortal, the test value needs nodecref. - Reading a name produces an owned temporary.
total + iincrefs both operands into temporaries, callsint_add, and decrefs both temporaries afterwards. Each incref is matched by a decref of the same temporary, so the pair changes nothing the program can see.bench-design.mdrecords that removing such pairs was examined and not implemented: across the hot paths the code generator cannot prove which pairs cancel (an assignment’sdecref, for one, releases a value that is really dead). - Assignment releases the old value.
total = ...decrefs whatevertotalheld before storing the new pointer. Oncetotalpasses 256 that object is a real heap int, so thedecreffrees it and the nextint_newtakes the same header back off the free list.
Every one of those calls is a call/ret pair, a few register moves and a tag compare. CPython runs the same loop as a handful of bytecodes, each with its own dispatch, but with no separate call per refcount change. Neither side is doing much work per pass; what differs is how the bookkeeping is spent.
The optimisations, and how each one works #
bench-design.md records four rounds of optimisation, each as a contained change with a before/after measurement on the reference machine. Each table below is that document’s record, best of 5, before and after the change in the same session. The rounds were measured on different days, so compare within a row, not across tables: the document itself says relative movement is the signal, because absolute bests drift with code layout from day to day.
Small ints, and the first skipped decref #
Most integers a program touches are small: counters, bounds, indexes, 0 and 1. The runtime keeps a table of 262 prebuilt int objects for -5 to 256, as CPython does, and int_new returns one of them instead of allocating:
runtime.s · int_newlines 753–789# ---- int_new ----------------------------------------------------------
# Input: rdi = i64 value. Output: rax = new owned int.
.p2align 4 # align function to 16 bytes
.globl int_new # make int_new visible to linker
.type int_new, @function # declare int_new as function
int_new: # entry, rdi holds raw int64 value
cmp rdi, -5 # below the cached range?
jl intnew_alloc # uncached negatives allocate fresh below
cmp rdi, 256 # above the cached range?
jg intnew_alloc # uncached positives allocate fresh below
lea rax, [rdi + 5] # rax = cache index 0..261 for value -5..256
imul rax, rax, 24 # rax = byte offset into the table (24 bytes each)
lea rcx, [rip + small_ints] # rcx = cache base (rip+index is illegal)
add rax, rcx # rax = cached immortal int, no alloc and no free ever
ret # return the shared singleton, like CPython's small-int cache
intnew_alloc: # uncached value: fall into the bump/free-list path
push rbp # save rbp for frame chain
mov rbp, rsp # rbp marks this frame
push rbx # save rbx, holds value (the only callee-saved reg this path uses; two pushes keep 16-alignment)
mov rbx, rdi # rbx keeps value across alloc
mov rax, [rip + free_int_head] # rax gets int free list head
test rax, rax # check if a recycled header is waiting
jz intnew_bump # bump-allocate when the free list is empty
mov rcx, [rax + 16] # rcx gets next free link from payload slot
mov [rip + free_int_head], rcx # pop the head off the free list
jmp intnew_fill # skip bump path, fill the recycled block
intnew_bump: # bump path for fresh 24 bytes
mov rdi, 24 # rdi gets 24 byte int size
call alloc_raw # get fresh bytes from arena
intnew_fill: # fill reused or fresh block
mov qword ptr [rax], 1 # set refcnt 1, one owned reference
lea rcx, [rip + type_int] # rcx gets address of int tag
mov [rax + 8], rcx # store int type at offset 8
mov [rax + 16], rbx # store boxed value at offset 16
pop rbx # restore rbx
pop rbp # restore rbp
ret # return new owned int in rax
The cached objects carry the immortal sentinel as their refcount, so aython_incref and aython_decref return immediately for them, as they do for True, False and None. The cache covers the same range as CPython’s, so is between two small ints answers as CPython does, and == compares ints by value either way. The same round stopped emitting the decref of aython_not’s result in if, while, and and or tests, since that result is always an immortal bool.
Recorded effect: fib30.py 0.085 s → 0.076 s, ratio 1.64x → 1.48x.
Arguments in registers #
A user call first passed every argument on the stack: a pad for alignment on odd counts, one push per argument, an add rsp to clean up, and a load-then-store in the callee. Now up to six arguments travel in the System V registers (rdi, rsi, rdx, rcx, r8, r9) with the count in r10d, and the callee checks the count before adopting them. In fib30.py the call site and the callee’s fast path are:
bench/programs/fib30.py · emitted · fn_fiblea rax, aython_none[rip] # rax = immortal None (borrowed, never freed)
mov [rbp-8], rax # init n = None (borrowed ref, no incref needed)
cmp r10d, -1 # general mode (pos list + kw dict)?
...
# adopt params: caller passed arg0..arg0 in registers, count in r10d
cmp r10d, 1 # arity check first: CPython raises TypeError here
jne abort_type # shared runtime stub: one stderr line, exit 1
mov [rbp-8], rdi # arg0: caller's owned ref, adopted not increfed
jmp .Lbody_fn_fib # fast path bound: join the body
.Lgeneral_fn_fib: # general-mode binding for an exact-positional def
...
mov rdi, [rbp-48] # arg0 -> register (owned ref travels with it)
mov r10d, 1 # argc for the callee's arity check
call fn_fib # rax = owned result; args adopted, not borrowed
mov [rbp-24], rax # park owned left operand (calls below would clobber rax)
...
mov rdi, [rbp-48] # arg0 -> register (owned ref travels with it)
mov r10d, 1 # argc for the callee's arity check
call fn_fib # rax = owned result; args adopted, not borrowed
mov [rbp-32], rax # park owned right operand
The arity check is one cmp and one jne that is never taken. Specialising it away was considered twice and rejected; the second time it was measured, by hand-editing the generated assembly, and replacing the ten bytes with ten nops timed the same as keeping them. bench-design.md also says this round let adopted parameter slots skip their None initialisation. In the current code they do not: every function now also has a general entry (r10d = -1) that binds keyword and *args calls from a list and a dict, and that path releases each slot’s initial None before storing, so the prologue initialises every slot again (fn_fib above still stores n = None first). The document records that the skip measured flat on its own, so nothing is lost.
| Program | ELF before | ELF after | Ratio before → after |
|---|---|---|---|
fib30.py |
0.075 s | 0.073 s | 1.44x → 1.39x |
callnull.py |
0.147 s | 0.133 s | 0.63x → 0.58x |
callargs4.py |
0.153 s | 0.168 s | 0.70x → 0.77x |
sum10m.py |
0.327 s | 0.323 s | 0.66x → 0.67x |
Int-first arithmetic, leaner boxing, cheaper lookups #
int_add used to test its operands against every sequence type before reaching the add. Now the int and bool tags are tested first and fall straight through to the shared compute block, which adds with the overflow flag watched; floats, lists, tuples and strings take the slow path:
runtime.s · int_addlines 791–911 push r15 # save r15, keeps stack aligned
mov rbx, rdi # rbx keeps left borrowed object
mov r12, rsi # r12 keeps right borrowed object
# Fast path first: both int-like goes straight to the add, skipping
# the six sequence-tag compares below (fib/sum loops live here).
mov rax, [rbx + 8] # rax = left tag at offset 8
lea rcx, [rip + type_int] # int boxes pass
...
lea rcx, [rip + type_bool] # True/False carry int payloads too
cmp rax, rcx # compare left tag against bool
jne .Ladd_seq # left is neither: sequence/error path
.Ladd_lint: # left int-like; same test for the right operand
mov rax, [r12 + 8] # rax = right tag at offset 8
lea rcx, [rip + type_int] # int boxes pass
cmp rax, rcx # compare right tag against int
...
lea rcx, [rip + type_bool] # True/False carry int payloads too
cmp rax, rcx # compare right tag against bool
je .Ladd_compute # both int-like: add at once
.Ladd_seq: # at least one side is not int-like: float, concat, or TypeError
mov rax, [rbx + 8] # rax = left tag at offset 8
lea rcx, [rip + type_float] # float tag?
cmp rax, rcx # compare left tag against float
...
cmp rax, rcx
je abort_type # int + str is a TypeError in CPython too
call check_intlike_rbx_r12 # both operands must be int-like; bools count as 1/0
.Ladd_compute: # both sides int-like (fast path or validated slow path)
mov rax, [rbx + 16] # rax gets left boxed value
add rax, [r12 + 16] # add right boxed value, sets flags
jo abort_overflow # abort OverflowError on signed overflow
mov rdi, rax # rdi gets raw sum for int_new
call int_new # box sum as new owned int
pop r15 # restore r15
int_new’s allocating path also stopped saving four registers it never used: the int_new listing earlier on this page pushes only rbp and rbx, the one callee-saved register that path uses. And dict_lookup gained a pointer-identity check before it compares hashes: the same object is always equal to itself, so a small-int key, or d[k] inside for k in d, never reaches obj_eq:
runtime.slines 4008–4069dict_lookup: # rdi = borrowed dict, rsi = u64 hash, rdx = borrowed key
push rbp # save caller frame pointer
mov rbp, rsp # start our stack frame anchor
push rbx # save callee-saved rbx
push r12 # save callee-saved r12
push r13 # save callee-saved r13
push r14 # save callee-saved r14
push r15 # save callee-saved r15
sub rsp, 16 # scratch: [rsp] = bucket index, [rsp+8] = owned eq bool
mov rbx, rdi # rbx keeps borrowed dict
mov r14, rsi # r14 keeps hash (survives the eq calls below)
mov r15, rdx # r15 keeps borrowed search key (survives the eq calls)
mov r12, [rbx + 32] # r12 keeps index buffer base
mov r13, [rbx + 40] # r13 keeps entry buffer base
mov rax, [rbx + 24] # rax = capacity for the mask
dec rax # mask = cap - 1 (cap is always a power of two)
mov [rsp + 8], rax # park the mask (capacity is stable: no grow mid-probe)
and rax, r14 # rax = start bucket = hash & mask
dict_lookup_probe: # linear probing: an empty slot ends the search
mov [rsp], rax # spill bucket index (the eq call below clobbers rax)
mov rcx, [r12 + rax*8] # rcx = index slot (0 = empty)
test rcx, rcx # empty bucket?
jz dict_lookup_miss # key is not in the dict
dec rcx # rcx = 0-based entry number
imul rcx, rcx, 24 # rcx = byte offset of the entry
lea rcx, [r13 + rcx] # rcx = entry address
mov rdx, [rcx + 8] # rdx = stored key object (borrowed)
cmp rdx, r15 # identical pointers are always equal (small-int singletons hit here, as does `for k in d: d[k]`)
je dict_lookup_hit # same object: skip the eq call entirely
cmp qword ptr [rcx], r14 # compare stored hash against search hash
jne dict_lookup_next # different hash cannot be our key
mov rdi, rdx # rdi = stored key object (borrowed for eq)
mov rsi, r15 # rsi = search key object (borrowed for eq)
call obj_eq # rax = owned immortal bool (eq_true/eq_false only ever return True/False singletons)
# No decref, spill, or reload: the result is provably immortal, so
# releasing it would be a no-op call and the pointer survives whole.
lea rcx, [rip + aython_true] # rcx = immortal True
cmp rax, rcx # check whether the keys compared equal
je dict_lookup_hit # equal keys: the spilled bucket is ours
dict_lookup_next: # advance one bucket, wrapping with the mask
mov rax, [rsp] # rax reloads spilled bucket index
inc rax # next bucket index
and rax, [rsp + 8] # wrap around the table with the parked mask
jmp dict_lookup_probe # test the next bucket
dict_lookup_hit: # recompute the entry address from the spilled bucket
mov rax, [rsp] # rax = winning bucket index
mov rcx, [r12 + rax*8] # rcx = index slot value
dec rcx # rcx = 0-based entry number
imul rcx, rcx, 24 # rcx = byte offset of the entry
lea rax, [r13 + rcx] # rax = entry address (hash/key/val run)
jmp dict_lookup_ret # hit: entry pointer in rax
dict_lookup_miss: # empty bucket: key absent
xor eax, eax # rax = NULL signals "not found"
dict_lookup_ret: # rax = entry address or NULL
add rsp, 16 # drop the scratch slots
pop r15 # restore r15
pop r14 # restore r14
pop r13 # restore r13
pop r12 # restore r12
pop rbx # restore rbx
pop rbp # restore caller frame pointer
ret # return to caller
| Program | ELF before | ELF after | Ratio before → after |
|---|---|---|---|
fib30.py |
0.073 s | 0.068 s | 1.42x → 1.32x |
sum10m.py |
0.347 s | 0.259 s | 0.69x → 0.54x |
dictlookup.py |
0.201 s | 0.177 s | 1.04x → 0.90x |
intsmall.py |
0.248 s | 0.195 s | 1.01x → 0.79x |
callnull.py |
0.128 s | 0.115 s | 0.55x → 0.50x |
The call tax: return forwarding and raw-bound tests #
Two kinds of ownership traffic were invisible to the program and still cost calls on every function return and every loop test.
return n used to incref n into the return slot and then decref it again in the shared epilogue: net zero, two calls. Now _emit_return moves the pointer instead and leaves the slot holding the immortal None, whose epilogue decref returns at the sentinel check.
n < 2 used to box the 2 with int_new, incref n into a temporary, compare, and release both: six calls. When the left side is a plain name and the right side an exact int constant, the code generator now passes the slot pointer and the raw constant to a leaf helper:
src/aython/codegen.py · _emit_compare_immlines 3728–3755def _emit_compare_imm(helper: str, name: str, bound: int, frame: Frame) -> list[str]:
"""Emit ``<local> <op> <int>`` via a raw-bound helper, borrowing the slot.
The bound travels in ``rsi`` as a raw i64 (no ``int_new`` box, no
right-operand decref), and the helper borrows the slot pointer
without consuming it, so the usual eval-incref/decref pair around a
``Name`` operand is pure overhead too: the slot keeps its reference
the whole time. Sound because the helper never stores, frees, or
otherwise retains its input (it only reads the tag and payload, or
aborts the process), and no slot access can interleave with the
call. Every loop-bound test in the bench corpus (``n < 2``,
``i < 5000000``) takes this path.
Args:
helper: Raw-bound runtime symbol, e.g. ``obj_lt_imm``.
name: Local slot name holding the left operand.
bound: Exact-``int`` constant bound, already range-checked to i64
by the frontend (``movabs`` covers the full range).
frame: Frame layout for the slot address.
Returns:
Assembly lines leaving the immortal bool result in rax.
"""
return [
f"mov rdi, {_slot(frame, name)} # borrow {name} directly (helper never consumes it; slot keeps ownership)",
f"movabs rsi, {bound} # raw bound in rsi: no box, no right-side cleanup",
f"call {helper} # rax = immortal bool (or aborts TypeError, like the boxed form)",
]
runtime.s · obj_lt_immlines 2693–2739# ---- ordering against a raw int: obj_lt/le/gt/ge_imm -------------------------
# Same result as the matching obj_* helper with a boxed int right side,
# minus the box: rsi carries the bound as a raw i64, so the caller skips
# both the int_new call and the right-operand decref. Borrow rdi and
# return the immortal bool directly (incref would be a no-op on it, so
# the owned/borrowed distinction collapses, like everywhere immortals
# cross the boundary). Ints and bools compare by payload (bool payloads
# are 0/1, like numeric_value); anything else aborts TypeError, exactly
# like obj_* with an int right side (sequences need a same-tag partner,
# strs/dicts/ranges fail numeric_value there). Leaf functions: no frame,
# no calls on the compare path, only caller-saved registers touched, so
# rsp stays aligned and rbx/rbp/r12-r15 survive untouched.
.p2align 4 # align code to 16 bytes for fast fetch
.globl obj_lt_imm # export less-than-against-int helper
.type obj_lt_imm, @function # mark symbol as a function
obj_lt_imm: # entry: rdi = borrowed object, rsi = raw i64 bound
mov rax, [rdi + 8] # rax = object tag at offset 8
lea rcx, [rip + type_int] # int boxes pass
cmp rax, rcx # compare tag against int
je .Lltimm_compute # int payload compares directly below
lea rcx, [rip + type_bool] # True/False carry int payloads too
cmp rax, rcx # compare tag against bool
jne .Lltimm_float # float left: exactness lives in the generic path
.Lltimm_float: # float left: box the bound, delegate to generic
push rbp # frame for the two calls below (3 pushes keep 16-alignment)
mov rbp, rsp # anchor the frame
push rbx # save borrowed-left holder
push r12 # save bound holder
mov rbx, rdi # park borrowed left (no calls ran yet)
mov rdi, rsi # arg = raw bound
call int_new # rax = owned boxed bound
mov r12, rax # park owned bound across the compare
mov rsi, rax # arg2 = boxed bound (helper borrows it)
mov rdi, rbx # arg1 = borrowed left
call obj_lt # exact generic compare, owned immortal bool out
mov rbx, rax # park owned bool (decref below clobbers rax)
mov rdi, r12 # arg = owned bound to release
call aython_decref # drop it (no-op on cached small ints)
mov rax, rbx # return the owned bool
pop r12 # restore bound holder
pop rbx # restore left holder
pop rbp # restore caller frame
ret # return owned bool in rax
.Lltimm_compute: # left int-like: payload against the raw bound
cmp qword ptr [rdi + 16], rsi # left payload vs bound
jl .Limm_true # less means True
jmp .Limm_false # otherwise False
Both show up in fn_fib’s base case:
bench/programs/fib30.py · emitted · .Lbody_fn_fibmov rdi, [rbp-8] # borrow n directly (helper never consumes it; slot keeps ownership)
movabs rsi, 2 # raw bound in rsi: no box, no right-side cleanup
call obj_lt_imm # rax = immortal bool (or aborts TypeError, like the boxed form)
mov [rbp-24], rax # park the owned test value
...
# line 3: return <expr> (park value, release locals, leave)
mov rax, [rbp-8] # take over n's owned ref (no incref: ownership moves)
lea rcx, aython_none[rip] # rcx = immortal None (borrowed, never freed)
mov [rbp-8], rcx # slot waits as None; its epilogue decref is a no-op
mov [rbp-16], rax # park the moved value before finally bodies clobber rax
Every while i < N loop in the benchmarks takes the raw-bound path too, which is why programs with no user calls at all moved in this round.
| Program | ELF before | ELF after | Ratio before → after |
|---|---|---|---|
fib30.py |
0.063 s | 0.045 s | 1.17x → 0.84x |
callnull.py |
0.111 s | 0.072 s | 0.47x → 0.30x |
callargs4.py |
0.159 s | 0.138 s | 0.72x → 0.63x |
sum10m.py |
0.253 s | 0.210 s | 0.53x → 0.44x |
dictlookup.py |
0.176 s | 0.150 s | 0.92x → 0.74x |
What was tried and not kept #
| Idea | Outcome | Reason recorded in bench-design.md |
|---|---|---|
| Fast paths for 0, 1 and 2 arguments that skip the arity check | Rejected twice | The check is one compare and a never-taken branch; replacing it with nops timed the same |
| Eliding incref/decref pairs | Not implemented | The hot pairs are not provably balanced: an assignment’s decref releases a value that is really dead |
Leaving the last argument in rax instead of a temporary |
Dropped | Measured flat on fib30.py: the memory operations all hit L1 |
| A frameless fast path for leaf functions | Rejected on analysis | Slots must be addressable across helper calls, and a function with try needs rbp for the unwinder; it would save three instructions per call |
Removing the epilogue decref of a forwarded slot |
Half done | The slot provably holds None, but the epilogue is shared by every return path, so the call stays |
bench-design.md also records a warning about method: the callnull.py loop proved so sensitive to code layout on that machine that shifting bytes without changing what executes moved it by up to 30%. Attributions were therefore checked with hand-edited single-change assemblies and nop controls, and with medians over interleaved pinned-core rounds, not with best-of-N alone.
What the numbers do not say #
- Anything about another machine. One machine, one day per table. The results file names its machine; rerun before quoting.
- Anything about small programs’ code. Below a few hundred milliseconds the ratio is mostly start-up.
- Variance. Best-of-N flatters both sides equally and hides spread; the per-round lists exist so a reader can look.
- Anything from CI. CI runs
aython bench --quick(two programs, one round) only to see that the harness still works, and never reads a number: timing on shared runners is noise. - How aython compares with other compilers. Only CPython is measured.
Where aython is slower or faster is a property of the design: boxed values, an explicit call for every ownership change, no inlining, no specialisation. The divergences chapter lists what that design gives up in behaviour; this chapter is what it gives up, and gains, in time.
Where this lives #
| Concept | Where |
|---|---|
| The harness | src/aython/bench.py bench_one, time_argv, render_markdown; src/aython/cli.py bench |
| The programs | bench/programs/ |
| The recorded results | bench/results/ |
| Method, regimes, every optimisation | docs/bench-design.md |
| Small-int cache | runtime.s small_ints, int_new |
| Immortal test values | src/aython/codegen.py _test_yields_immortal |
| Register arguments | codegen.py _emit_fast_call (call site), _emit_function (callee prologue and adoption), REG_ARG_ORDER |
| Int-first arithmetic | runtime.s int_add, int_mul, the ordering compares |
| Identity-first dict lookup | runtime.s dict_lookup |
| Return forwarding | codegen.py _emit_return |
| Raw-bound tests | codegen.py _emit_compare_imm, _CMP_IMM_HELPERS; runtime.s obj_lt_imm, obj_le_imm, obj_gt_imm, obj_ge_imm |
| This page’s data | docsite/figures/bench.py, docsite/figures/speed.py |
Check yourself #
Check yourself
dictbench.pyrecords an ELF best of 0.001 s and a CPython best of 0.008 s. What does its ratio mostly measure?- How fast aython’s dict probe is
- How long CPython takes to start, against an ELF that starts almost immediately
- The cost of
int_add
Answer
How long CPython takes to start, against an ELF that starts almost immediately. The whole program takes about a millisecond on the ELF. CPython’s time is dominated by starting the interpreter, and three-decimal rounding makes the ELF figure itself uncertain by a factor of three.Why does
benchalternate which side runs first in each round?- So that slow drift in the machine does not always favour the same side
- So that CPython’s caches are warm
- Because the ELF must run before CPython to be checked
Answer
So that slow drift in the machine does not always favour the same side. Even rounds run the ELF first, odd rounds CPython first. A machine that slows down or speeds up over the run then affects both sides alike.In
while i < 10000000:, what does the current code pass toobj_lt_imm?- Two boxed ints, both owned
- The slot pointer for
i, borrowed, and the raw integer 10000000 inrsi - The raw value of
iand a boxed 10000000
Answer
The slot pointer fori, borrowed, and the raw integer 10000000 inrsi._emit_compare_immloads the slot intordiwithout an incref and the constant intorsiwithmovabs; no box is made and nothing needs releasing.fib30.pyhas a ratio above 1 in the recorded file. Why does the fitted per-call cost put the ELF further behind than the ratio does?- Because the ELF’s start-up is slower than CPython’s
- Because CPython’s total includes several milliseconds of start-up the ELF does not pay, which dilutes the per-call difference in the ratio
- Because the ratio is taken over medians
Answer
Because CPython’s total includes several milliseconds of start-up the ELF does not pay, which dilutes the per-call difference in the ratio. Total time is start-up plus work. CPython pays more start-up, so its total is closer to the ELF’s than its per-call cost is.return nin a function used to cost an incref and an epilogue decref. What does it cost now?- No incref: the pointer moves to the return slot, the variable’s slot is set to the immortal
None, and the epilogue’sdecrefof that slot returns at once - One incref
- One decref, in the caller
Answer
No incref: the pointer moves to the return slot, the variable’s slot is set to the immortalNone, and the epilogue’sdecrefof that slot returns at once._emit_returnmoves the owned reference; the slot’sdecrefin the shared epilogue then seesNoneand returns at the sentinel check.- No incref: the pointer moves to the return slot, the variable’s slot is set to the immortal