Skip to content

Add an x86-64 assembly engine: 9.8x faster than Rust, 322x faster than Python - #35

Merged
dhh merged 187 commits into
masterfrom
asm-zen5
Sep 26, 2026
Merged

dhh merged 187 commits into
masterfrom
asm-zen5

Conversation

@dhh

@dhh dhh commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Adds an x86-64 assembly engine for all 37 effects, linked into the Rust binary and picked automatically at runtime. It produces byte-identical output to the Rust engine: 9.8× faster than Rust on two cores (7.5× on one), and 322× faster than the original Python TerminalTextEffects (geometric means).

How it fits in

  • asm/ holds the engine, in NASM. build.rs assembles it once per CPU tier into libttfx_asm.a, behind the asm feature (on by default). If NASM is missing, the build warns and produces the pure-Rust binary.
  • Rust stays the front end: CLI, input, RNG seeding and signals. Each run is offered to the asm engine, which either declines before doing anything observable or runs the effect to the end.
  • Every effect and option is supported, including ANSI input, --wrap-text and all --existing-color-handling modes.
  • CPU tiers: x86-64 v1 (SSE2), v2, v3 (AVX2) and v4 (AVX-512). The best one the CPU supports runs automatically, so every x86-64 CPU gets the asm engine. Other architectures, or a build without NASM, use the Rust engine.
  • Threads: unpaced runs with two or more CPUs format and write frame N on a second thread while the main thread computes frame N+1. Paced runs stay single-threaded.
  • Environment switches:
    • TTFX_ASM=0 forces the Rust engine.
    • TTFX_ASM=force uses asm, exiting 3 if it declines.
    • TTFX_ASM_TIER=n forces a tier.
    • TTFX_ASM_THREADS=1 forces one thread.
    • TTFX_ASM_SHOW_TIER=1 prints which engine ran, and why.
  • Docs: plans/asm-x86.md has the design, tiers and results. asm/PORTING.md is the working manual and engine API reference.

Verification

  • tools/asm/oracle.sh compares stdout, stderr and the exit status of TTFX_ASM=0 against TTFX_ASM=force. It covers:

    • seeds, anchors, clipping, tabs, \r, UTF-8, wrapping and parity dumps;
    • every option set in tools/asm/cases/, each also run against ANSI input under always and dynamic color handling.

    Option sets that the Rust engine rejects must be marked as intended error tests, so a mistyped case can't pass by comparing two identical error messages.

  • All 37 effects pass at all four tiers, threaded and single-threaded (oracle-tiers.sh).

  • The same effects pass on emulated older CPUs under qemu-user: qemu64 is tier 1, Nehalem tier 2, Haswell tier 3 (qemu-oracle.sh). The right tier is auto-selected on each.

  • isa-audit.sh checks every tier's object and finds no instruction above that tier's budget.

  • Real ttys and signals are covered by pty_compare.py, sigtest.py, resizetest.py and closetest.py: pacing, SIGINT/SIGTERM teardown, resize reruns and closed readers.

  • cargo test --release --test asm_diff passes, 21 tests.

  • It runs on real tier-3 hardware too: on a Core Ultra 5 135U (no AVX-512) it is 8.16× faster than Rust on a single E-core.

  • A Codex review of every effect found three bugs and one leak, all fixed:

    • NaN path speeds from inf-inf ranges;
    • oversized option values;
    • silent test gaps;
    • thunderstorm's unbounded memory on very long storms.

Performance

Measured on a quiet Ryzen 9 9955HX (Zen 5) with tools/asm/speed.py --python: 200×50 canvas, 190×46 text, --frame-rate 0, output to /dev/null, best of 3–5 runs.

  • 1 core is pinned to one CPU. The engine runs single-threaded, which is the like-for-like comparison with the single-threaded Rust engine.
  • 2 cores is pinned to two physical cores, with the render thread on.
  • Python is TerminalTextEffects 0.15.0 on CPython 3.14.7, one run per effect, compared with the 2-core asm time.
  • matrix and thunderstorm run for a fixed wall-clock time. Rust and asm use --virtual-clock for them, and they have no Python ratio.
effect Python ms Rust ms asm ms (2 cores) vs Rust, 1 core vs Rust, 2 cores vs Python
beams 7,416 206.5 11.3 13.2× 18.3× 656×
binarypath 19,840 709.0 135.0 3.4× 5.2× 147×
blackhole 11,890 351.8 50.2 5.4× 7.0× 237×
bouncyballs 9,049 282.0 25.4 7.6× 11.1× 357×
bubbles 13,734 413.5 34.4 7.2× 12.0× 399×
burn 8,522 304.3 18.1 10.4× 16.9× 472×
colorshift 6,783 299.7 17.7 15.5× 16.9× 384×
crumble 8,664 251.0 42.7 4.2× 5.9× 203×
decrypt 10,410 380.4 16.4 19.3× 23.2× 634×
errorcorrect 7,690 245.3 17.6 9.8× 13.9× 437×
expand 3,704 95.4 14.5 4.9× 6.6× 256×
fireworks 18,098 295.6 56.4 4.0× 5.2× 321×
highlight 1,446 37.9 3.4 11.3× 11.1× 423×
laseretch 18,640 488.1 40.0 7.0× 12.2× 466×
matrix n/a 153.1 18.5 5.7× 8.3× n/a
middleout 2,576 69.1 9.6 6.3× 7.2× 269×
orbittingvolley 2,032 57.4 13.5 2.9× 4.3× 151×
overflow 2,725 94.7 10.7 6.5× 8.9× 255×
pour 6,818 196.5 15.4 9.1× 12.8× 444×
print 8,347 264.1 7.5 32.4× 35.2× 1114×
rain 5,360 166.1 17.8 6.5× 9.3× 300×
randomsequence 1,243 40.3 3.7 9.1× 11.0× 340×
rings 12,681 553.4 94.2 4.6× 5.9× 135×
scattered 4,027 117.4 19.4 4.0× 6.0× 207×
slice 2,751 52.9 7.4 6.4× 7.1× 371×
slide 2,691 75.8 10.2 5.1× 7.5× 265×
smoke 3,917 160.0 10.4 11.9× 15.4× 377×
spotlights 9,857 260.8 29.1 7.9× 8.9× 338×
spray 3,425 120.3 23.6 3.6× 5.1× 145×
swarm 17,582 574.5 79.1 4.9× 7.3× 222×
sweep 1,683 52.8 5.5 10.1× 9.7× 307×
synthgrid 2,680 102.3 7.0 15.0× 14.6× 383×
thunderstorm n/a 243.3 20.7 11.3× 11.7× n/a
unstable 5,125 142.9 27.5 3.5× 5.2× 186×
vhstape 7,167 182.7 25.0 6.5× 7.3× 287×
waves 10,669 410.6 15.2 22.2× 27.0× 703×
wipe 1,361 35.1 3.3 10.3× 10.7× 416×
geometric mean 7.53× 9.79× 322×

For reference, Rust alone is 33× faster than Python on the same run. When every effect had first been ported, before the speed work, the 1-core figure was 4.11×.

Where the speed comes from, roughly in order of effect:

  1. Data layout: characters as structure-of-arrays, pooled visuals, and an incremental cell grid with per-row output buffers.
  2. Removing repeated work:
    • path cursors;
    • memoized easing;
    • visuals interned by header;
    • "dozing" characters that skip ticks where nothing visible changes;
    • frame and segment lists shared between characters;
    • scenes cloned instead of rebuilt.
  3. Memory effects: staggering arrays to avoid 4K aliasing, prefetching the next frame, and huge-page control.
  4. SIMD and threads: batched motion 8 or 4 lanes wide, an 8-lane RNG, and the render thread.

The slowest effects are orbittingvolley, spray, fireworks, binarypath and unstable. They are bound by the main thread's motion batch.

Reproduce with tools/asm/speed.py [--core 8,9] [--python]. speed.py --help explains how to install Python TTE.

Build note

On x86_64 Linux the build assembles the engine with NASM ≥ 3.0, found via $NASM or PATH (pacman -S nasm). If NASM is missing, the build warns and produces the pure-Rust engine. --no-default-features also leaves the asm engine out. Other platforms are unaffected.

🤖 Generated with Claude Code

https://claude.ai/code/session_01MxJcVYpBxFDam6czK4bGjp

dhh and others added 30 commits September 25, 2026 09:47
Rust stays the front end: it parses arguments, reads the input and seeds
the RNG, then offers the run to the assembly engine (asm/, built by
build.rs with NASM). The engine declines anything it has not ported, before
producing output, so the Rust engine runs it instead. TTFX_ASM=0 forces
Rust; TTFX_ASM=force fails instead of falling back, which is what
tools/asm/oracle.sh uses to compare the two engines byte for byte.

Decrypt is the first effect: 206/206 oracle cases identical, 14.5x faster
at 200x50 (371 ms -> 25.5 ms).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
asm/PORTING.md is the working manual for porting effects and utilities:
conventions, PIC rules, matching the oracle's compiled float code, and how
to verify. tests/asm_diff.rs compares asm functions with their Rust
originals, starting with randint, uniform and shuffle.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
asm/utils/pycompat.asm: round_half_even, floor_div, py_mod and the
saturating f64_to_i64 cast, with pycompat.rs's non-finite rounding.

asm/utils/geometry.asm: every pub function of src/utils/geometry.rs on
packed u64 coordinates, plus the streaming ellipse. The float lowering
mirrors the compiled oracle: powf(x, 2.0) as x * x, powf(x, 0.5) as
sqrtsd with LLVM's fabs and -inf fix-ups, the sin/cos pair as sincos,
lengths through glibc hypot, and the bezier length's omitted final span.

asm/utils/color.asm: adjust_color_brightness, shift_color_towards and
random_color on the u64 color format, in the oracle's operation order.

tests/asm_diff.rs compares every function with Rust bit for bit on
boundary, degenerate and random inputs, and the color functions over all
256 values of each channel crossed with many factors.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The engine now covers what effects need beyond decrypt:
- chars.asm: the character store as fixed-capacity SoA regions, fill
  characters, neighbors and the input-coordinate map
- terminal.asm: get_characters with all seven sorts and
  get_characters_grouped with all ten groupings, canvas helpers
- scene.asm: named scenes with plain, synced and eased playback, looping,
  gradients (cyclic distribution) and set_appearance
- events.asm: the event table with reentrant, append-safe dispatch
- motion.asm: paths, waypoints, segments and the exact Path.step walk
- update.asm and particles.asm: the active set, update and particle pools
- easing.asm (ported by Codex): all 31 easings, EasingTracker and
  SequenceEaser, bit-identical to the oracle over 4.3M comparisons

Decrypt runs on the general engine: 206/206 oracle cases, 32.5 ms against
Rust's 371 ms.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Ported on cph-a2 by a Claude agent: every geometry function, pycompat
rounding and Python integer division, adjust_color_brightness,
shift_color_towards and random_color, each checked against Rust in
tests/asm_diff.rs. Motion and gradients now use these instead of the
interim path geometry.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
synthgrid_build/synthgrid_next_frame transcribe src/effects/synthgrid.rs:
grid lines as consecutive added slots with an extended prefix, blocks as
one flat member array, the group tracker as an effect callback, and a
memo of the dissolve visuals. marshal packs the grid/text gradients, the
grid symbols, the generation symbols and max_active_blocks.

oracle synthgrid full: 1766 passed, 0 failed.
200x50: Rust 108 ms, asm 14 ms (best of 5, pinned).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
vhstape_build / vhstape_next_frame transcribe src/effects/vhstape.rs:
per-character glitch, restore and wave paths, the six scenes, the
glitch wave, glitch lines, noise and the line-by-line redraw, with
every RNG draw in Rust's order. Snow visuals are memoized per
(color, symbol), and lines are the engine's row groups.

oracle.sh vhstape full: 1958 passed, 0 failed.
200x50, best of 5: Rust 190 ms, asm 44 ms.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
blackhole_build / blackhole_next_frame transcribe src/effects/blackhole.rs
draw for draw: ring selection, starfield, singularity, collapse and
explosion. Starfield visuals and their fades are made once and reused;
phase checks use a membership bitmap over the active set.

Every option is supported; tools/asm/oracle.sh blackhole full passes.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
# Conflicts:
#	asm/effects/registry.asm
#	src/asm/effects.rs
Groups come from get_characters_grouped and are eased with the asm
SequenceEaser; each character gets one "wipe" scene whose gradient runs
from the final spectrum's first color to its mapped final color (reused
while consecutive characters share that color). The dynamic
existing-color branch is ported too. Final gradient frames outside the
i32 range are declined in marshal; values below 1 fail like Rust.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Every option is supported: all ten highlight directions, brightness,
width and the final gradient. The highlight spectrum is recomputed only
when a character's base color changes from the previous character's.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Both sweeps' scenes are built in Rust's order so every RNG draw lines up;
the SequenceEaser walks the first direction's groups, then the second's.
Visuals are memoized per (symbol, color). Dynamic color handling is
ported (input-color palette with the spectrum fallback).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Transcribes src/effects/random_sequence.rs: the final gradient mapped over
the text, one 8-frame fade from the terminal background per character
(dynamic color handling included), a shuffled reveal of characters_per_tick
characters per frame. Frame durations beyond 32 bits are declined.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Rings gives every ring character one single-waypoint path per ring
coordinate, chained in a loop. The port keeps one engine path per ring
character that stands in for all of them: activating ring path k points
its waypoint at the k-th rotated coordinate and swaps in path k's own
total and origin distance, so each path's rounding history is kept
exactly. The chain becomes a callback, which keeps event lookups short.

The engine gains path_reset (motion.asm) for the "disperse" path that
Rust removes and recreates every cycle.

oracle.sh rings full: 2342 passed. 200x50, best of 5: Rust 0.577 s,
asm 0.145 s.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A screen map keyed by (row, column) replaces the one-row buffer, so cursor
movement and overwrites behave as in input.rs: SGR colors (xterm and 24-bit,
with its widening quirk), the four ignored private modes, CSI cursor moves,
OSC and bare escapes with Rust's error text, input color frequencies,
preexisting_colors_present, and existing-color-handling always at creation.
Rust still declines ANSI input until the oracle covers it.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
# Conflicts:
#	asm/effects/registry.asm
#	src/asm/effects.rs
# Conflicts:
#	asm/effects/registry.asm
#	src/asm/effects.rs
# Conflicts:
#	asm/effects/registry.asm
#	src/asm/effects.rs
# Conflicts:
#	asm/effects/registry.asm
#	src/asm/effects.rs
matrix.asm transcribes src/effects/matrix.rs: rain columns as fixed
records (pending as an index, visible as a start/end window), a pending
ring and active/full index arrays, the wall-clock rain deadline through
clock_wall, and current symbols/colors read back with visual_meta. The
dynamic existing-color branch is ported too.

Color == compares hex spellings, so the marshalling tags hex stops spelled
unlike Color::from_rgb (bits 48+, ignored by rendering and color math).

Engine: RNG_BITS53 and rng_threshold (rng.asm) decide random() < c as an
integer compare with the batch read inlined, tested against Rng::random in
asm_diff. oracle.sh gains "@global <args>" in case files; matrix uses it
for --virtual-clock, since real-clock frame counts are not reproducible.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Every option is supported, including the dynamic existing-color branch.
oracle expand full: 2726 passed; 200x50 run: Rust 109ms, asm 51ms.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Every option is supported: all nine spray positions, volume, speed range,
movement easing and the final gradient. The dynamic existing-color branch is
ported too, for when the input side lands.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
scattered_build/scattered_next_frame transcribe Scattered::build and
next_frame: a random start per character, one auto path home with the
SetLayer events, and a distance-synced gradient scene (the last character
gradient is reused while the final color repeats). The dynamic color branch
is ported too. Frame durations outside i32 are declined in marshal.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
# Conflicts:
#	asm/effects/registry.asm
#	src/asm/effects.rs
# Conflicts:
#	asm/effects/registry.asm
#	src/asm/effects.rs
@dhh dhh changed the title Add an x86-64 assembly engine for all 37 effects Add an x86-64 assembly engine: 9.8x faster than Rust, 322x faster than Python Sep 26, 2026
@dhh
dhh merged commit 73c7a44 into master Sep 26, 2026
3 checks passed
@TilakMaddy

TilakMaddy commented Sep 26, 2026 •

Copy link
Copy Markdown

Chill guys, there are many software modules written pre AI that did single-architecture optimizations with fallback logic for the rest. Sure, not many people were tweeting about it. Also do you know what happens behind LLVM, do you think it optimizes IR for all architectures equally? Of course not, it tries to take advantage of what's unique!

@dhh dhh mentioned this pull request Sep 26, 2026
3 tasks done
@dhh
dhh deleted the asm-zen5 branch September 26, 2026 19:45
@koolkdev

Copy link
Copy Markdown

Chill guys, there are many software modules written pre AI that did single-architecture optimizations with fallback logic for the rest. Sure, not many people were tweeting about it. Also do you know what happens behind LLVM, do you think it optimizes IR for all architectures equally? Of course not, it tries to take advantage of what's unique!

Did you look on this PR? Most of it is doing the compiler job and just rewriting regular assembly functions. Architecture-specific optimizations is exposing hardware specific primitives or writing specific functions that use them in assembly, while making most of the code shared between the architectures. Otherwise it is just a recipe for maintenance hell without any real gain.

@mateolafalce

Copy link
Copy Markdown

This PR is historic. If the ultimate goal is the output the user receives, moving from low-level languages to assembly makes sense for a project like this.

@hegjon

hegjon commented Sep 27, 2026

Copy link
Copy Markdown
Contributor

It is a good project to test ideas like this on. Small tool, few dependencies and a good test suite

@gamenerds

Copy link
Copy Markdown

lolololololololololol

@Glass109

Copy link
Copy Markdown

Killed portability just to own the l33ts, great job

@nonetrix

nonetrix commented Sep 28, 2026 •

Copy link
Copy Markdown

Chill guys, there are many software modules written pre AI that did single-architecture optimizations with fallback logic for the rest. Sure, not many people were tweeting about it. Also do you know what happens behind LLVM, do you think it optimizes IR for all architectures equally? Of course not, it tries to take advantage of what's unique!

Yes, but usually places where it makes way more sense e.g. game engines (not as common anymore pretty sure), web browsers a tad pretty sure, kernels, embedded stuff, and video encoding/decoding etc. I will admit I misunderstood the PR a bit and it's implications slightly, and maybe worded my comment poorly. That said I still maintain priorities are being misplaced. Just creates extra maintenance for realistically zero gain.

There is far bigger issues with Omarchy when I tried it a month ago, the screensaver being slow was never one of them. I don't think any of the actual issues/critiques I had have been addressed. If perfection is the goal, basics should be out of the way first before getting distracted, and in my opinion perfection should expand to code maintainability and readability etc.

Regardless, please remain civil and purely technical ideally. This PR won't spawn a black hole and end the world, it won't kill your cat either, or make Starship explode in orbit in 6 hours... Did you know Starship is going orbital finally? The tallest and most powerful rocket in history beating the Saturn V while being fully reusable soon. All I can think about right now, not this PR. I'd advise everyone heated over this do the same, think about something else, maybe touching grass if you don't have my exact interests.

@gnosisHermes

gnosisHermes commented Sep 28, 2026 •

Copy link
Copy Markdown

This dude is truly smoking something that is mind altering and i think he should share it

"The pursuit of excellence requires no justification"

So excellence means ABSOLUTE THROUGHPUT rather than ABSOLUTE USABILITY

Hell. people are psychotic with all this vibecoding. And trust me i'm psychotic as well but... fuck

I have unlimited tokens. We can fix everything, we can do anything.

Oh pardon me, Mr Gucci Loafers

Also, that sounds like a Dutch Van Der Linde quote "just have some goddamn faith"

@jedace07

Copy link
Copy Markdown

millions of dollars into this but not into projects that bring actual value like gnome kde or flathub yeah we're never getting a year of the linux desktop 🥀

@gnosisHermes

Copy link
Copy Markdown

woah woah, you're calling "gnome", "kde" or "flathub" "projects that bring actual value"

Damn. This guy here is more psychotic than the one that thought rewriting this in ASM was a good idea.

@jedace07

Copy link
Copy Markdown

sorry man I forgot that the masses yearn for suckless DWM and recompiling kernels every day, I forgot KDE and GNOME were evil and bloated 👍

@gnosisHermes

Copy link
Copy Markdown

I'm glad you understand.

@detomastah

Copy link
Copy Markdown

So rust is 10x slower than assembly? Good to learn.

@elictl

elictl commented Oct 1, 2026

Copy link
Copy Markdown

the pursuit of excellence requires no justification

@gnosisHermes

Copy link
Copy Markdown
1790691469561197

@KatPurpy

KatPurpy commented Oct 9, 2026 •

Copy link
Copy Markdown

the pursuit of excellence requires no justification

I am very sorry.

Yeah, but your scientists were so preoccupied with whether or not they could, they didn't stop to think if they should.
- Dr. Ian Malcolm, Jurassic Park

edit: also another funny reference for the readers to think about:

'Now! Now!' cried the Queen. 'Faster! Faster!' And they went so fast that at last they seemed to
skim through the air, hardly touching the ground with their feet, till suddenly, just as Alice was getting
quite exhausted, they stopped, and she found herself sitting on the ground, breathless and giddy.
The Queen propped her up against a tree, and said kindly, 'You may rest a little now.'
Alice looked round her in great surprise. 'Why, I do believe we've been under this tree the whole
time! Everything's just as it was!'
'Of course it is,' said the Queen, 'what would you have it?'
'Well, in OUR country,' said Alice, still panting a little, 'you'd generally get to somewhere else--if
you ran very fast for a long time, as we've been doing.'
'A slow sort of country!' said the Queen. 'Now, HERE, you see, it takes all the running YOU can do,
to keep in the same place. If you want to get somewhere else, you must run at least twice as fast as
that!'
- Through the Looking Glass and what Alice found there, Lewis Carroll

@pcrav0

pcrav0 commented Oct 16, 2026

Copy link
Copy Markdown
this-is-fine

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.