Repository navigation
Mimic 0.4.0
Stage 0.4.0, the measuring stick: a benchmark corpus of 130 everyday algorithms (hashing, parsing, graphs, text, interpreters, compression, numbers, simulations, geometry, images, data structures and dynamic programming), each in Mimic, C and Rust and checked against an independent reference; the machine's limits; and a speed gate on Linux, macOS and Windows that fails CI on a slowdown. The corpus found the bugs and slow paths fixed below, and the gaps left for the rest of stage 0.4 (docs/gaps.md). Its algorithms also became standard modules: hash, text, graph, order, parse, compress, and whole numbers in math.
Changed
- The standard library's own records hold raw numbers, as a program's do: its private helper records (the state of
hash,graph,compress,math::primes…) kept every number boxed, so their loops ran 2–15× slower than the same code in a program (math::primes(10000000): 5.0 s → 0.35 s;compress::rleof 4 MB: 1.2 s → 0.15 s). Public types, which the runtime builds too, keep their layout. sieveandkmeansare written as one would write them:sievekeeps its flags in bytes, as C does, andkmeanspasses its centres as a record. Both workarounds are gone now thatputon bytes is in place and a record passed along a recursion is borrowed.- The speed gate times short benchmarks longer: each side runs until it has run for a second (at most 30 runs) before the best time is taken. Benchmarks of 50–130 ms raised false alarms of 6–22% with the best of 3.
- The gate's noise is measured as the gate compares:
bench/run.py --noisenow runs the gate's comparison with the same compiler on both sides; a benchmark too noisy for the 25% limit on a platform is reported there, not gated. (The first noise data, ratios to C across whole rounds, overstated it, and a preview's identical compiler failed the gate ontreeandui.) - Benchmarks against C and Rust only: the Go versions are gone, from the suite and from the tables in BENCHMARK.md and on the website. The http benchmark's load generator is now a Rust program (
bench/http/load/main.rs).
Added
- Whole numbers in
math, from the corpus:math::gcd,lcm,powmodandmulmod(exact for anyi64, with 128-bit products),is_prime(Miller-Rabin, exact for everyi64),primes(a sieve) andtotient, checked against Python and sympy. Golden testmath_whole, docs/std.md and the tutorial. compress, from the corpus:compress::rle/unrle,compress::lzw/unlzw(12-bit codes) andcompress::varints/unvarints(zigzag LEB128 deltas), checked against reference implementations in Python, with every round trip and each decoder'sErrfor input it did not make. Golden testcompress_module, docs/std.md, the tutorial (chapter 16) and man pages.orderandparse, from the corpus:order::lower_bound,upper_bound,select(quickselect) andmerge, checked against Python'sbisectandsorted;parse::csv(RFC 4180, against Python'scsv),parse::url(againsturllib.parse.urlsplit) andparse::semverwithsemver_compare(against the precedence chain of semver.org). Golden testorder_parse, docs/std.md, the tutorial (chapter 6) and man pages.graph, from the corpus:graph::bfs,graph::shortest(Dijkstra with a binary heap),graph::components(union-find),graph::topo(Kahn's algorithm,Nonefor a cycle) andgraph::mst(Kruskal), on nodes 0 … n - 1 and edges as lists, checked against networkx on graphs of up to 20,000 nodes. Golden testgraph_module, docs/std.md, the tutorial (chapter 6) and man pages.text, from the corpus:text::distance(Levenshtein, by characters),text::find_all(every occurrence, overlapping, by KMP),text::soundexandtext::wrap(greedy, as Python'stextwrap), checked against Python and Soundex's published examples. Every loop is a loop in debug builds too, so a pattern that falls back far or a long name cannot exhaust the stack. Golden testtext_module, docs/std.md, the tutorial (chapter 6) and man pages.hash, the first module graduated from the corpus:hash::crc32,crc64,adler32,fnv1a32,fnv1a64,murmur3,xxhash32,xxhash64,siphash,md5,sha1andsha256on bytes, checked at every length around their block sizes against Python'szlib,hashlib,xxhashandmmh3and the published test vectors, in optimised and debug builds alike. Byte-by-byte loops run in chunks, so a debug build hashes any size without running out of stack, and an optimised one as fast as the benchmark's loop. Golden testhash_module, a section in docs/std.md and the tutorial (chapter 16), and man pages (mimic man hash).- The corpus reaches 130: 41 more everyday algorithms in Mimic, C and Rust, each checked against an independent reference: numbers (
gauss,millerrabin,coprime,totient,partitions,fibmod,catalan,polyeval,bigfact), simulations (shuffle,randwalk,ising,sandpile,rule110,traffic,langton), puzzles (tsp,sudoku,knight,matchain), graphs (mst,bellman,bipartite,flood,maze), data structures (lru,rangemin,intervals,bitset), text (roman,soundex,wordwrap,xmltags,markdown,template,lisp), hashing and ciphers (crc64,sha1,chacha20),base32anddct. On one core on the M-series Mac most are within 1-2× of C (intervals,mst,bellman,ising,partitions,sha1andbase32faster); the slowest are text built piece by piece (markdown4.9×,xmltags4.4×,soundex3.6×,roman3.5×),tsp4.2× (the table rewritten for each set size),sudoku3.8× (a new board for each placement) andflood3.4× (a pair made for each neighbour). Writing them found the fixes above, and gaps recorded in docs/gaps.md. - The corpus, more text:
zalgo(Z-algorithm),manacher(Manacher's palindromes) andanagram(anagram classes), in Mimic, C and Rust, checked against Python. On one core on the M-series Mac, against C:manacher1.9×,zalgo3.2× (sequential passes thatputinto a list held by a record: 0.4.3),anagram6.5× (half a million words built letter by letter as strings). - The corpus, geometry:
hull(convex hull by monotone chain),pip(point in polygon by ray casting) andsegments(segment intersection, all pairs), in Mimic, C and Rust, in exact integer arithmetic, checked against Python. On one core on the M-series Mac, against C:hull0.75× (sorting one number per point),segments1.1×,pip1.3×; on all cores 2.2–4.5× faster than C. Found on the way:(a > y) != (b > y)is refused as a chained comparison, and a long condition cannot be split over lines except inside parentheses (docs/gaps.md). - The corpus, more parsing, and servers:
numparse,semverandini(checked against Python,iniagainstconfigparser), and two servers with their own load generators:http_route(a JSON API with path parameters and 404s) andhttp_echo(POST bodies answered in upper case), in Mimic, C and Rust (hyper). On one core on the M-series Mac, against C:http_echo0.96×,http_route1.6×,numparse2.4×,semver3.2×,ini4.0× (eachsliceandtrimmakes a new string: docs/gaps.md, 0.4.12); on all cores both servers match or beat the single-threaded C server. - The corpus, more compression and hashing:
varint(zigzag LEB128 deltas),bitpack(13-bit values in 64-bit words),lzw,xxhash64,md5andsiphash(SipHash-2-4), in Mimic, C and Rust, checked against Python (xxhash,hashlib, and the SipHash paper's test vector). On one core on the M-series Mac, against C:bitpack1.8×,md51.4×,xxhash641.6×,varint3.9×,lzw3.8×,siphash22× (its rounds return the state as a tuple, which is allocated: docs/gaps.md, 0.4.3).bitpackpacks and unpacks as one parallel map each; the hashes loop with a function that calls itself, which is many times faster than asettleover a tuple. Found on the way: deep recursion through a function that takes a list or returns a tuple can still overflow the native stack past ~50,000 levels, with no message (docs/gaps.md); a type name for a tuple is not accepted. - The corpus, dynamic programming:
lcs(longest common subsequence, each row one map and onetrail(⌈)),coins(ways to make change) andlis(longest increasing subsequence by patience sorting), in Mimic, C and Rust, checked against Python. On one core on the M-series Mac, against C:lis0.7×,lcs1.5×,coins4.3× (a step thatputs into a list held by a record goes through the record each time: docs/gaps.md, 0.4.3). Found on the way:gatherwith a lambda goes through the runtime one boxed pair at a time (docs/gaps.md, 0.4.1). - The corpus, sorting and searching:
radix(LSD radix sort),bsearch(binary search, lower bounds) andselect(quickselect), in Mimic, C and Rust, checked against numpy. On one core on the M-series Mac, against C:bsearch0.9×,select1.6×,radix4.8× (everyputof its placing pass is a call into the runtime: docs/gaps.md, 0.4.3). A bottom-up merge sort is written but waits for lists built from pieces to keep their type (docs/gaps.md). - The corpus, images:
histeq(histogram equalization),rotate(90° turns),dither(Floyd–Steinberg error diffusion) andintegral(a summed-area table and 8,000,000 box sums), in Mimic, C and Rust, checked against Python (numpy for all butdither). On one core on the M-series Mac, against C:histeq1.7×,rotate1.6×,dither2.2×,integral1.5×; on all cores each is faster than C (frames, rows and boxes run in parallel). Found on the way: a lambda kept in aletand called in a hot loop is 15–40× slower than the same named function (docs/gaps.md, for 0.4.1). - The corpus, data structures:
bloom,hashmap,heapandfenwick, in Mimic, C and Rust, checked against Python. Each updates a list in place step by step (evolvewith a named step,putthrough a record) and reads it in parallel. On one core on the M-series Mac:bloom1.5× C,hashmap2.1×,heap2.1×,fenwick1.9×. Writing them foundevolve/settlewith named functions copying the state at every step (fixed), and a list passed bare to a function thatputs into it being copied at everyput(docs/gaps.md). - The corpus, puzzles and tables:
nqueens,knapsack,floydandcollatz, in Mimic, C and Rust, checked against Python (numpy forfloyd). On one core on the M-series Mac:nqueens0.9× C (0.53 s on all cores, with the parallel map fix),knapsack2.0×,floyd2.9×,collatz2.4×. Writing them found two gaps (docs/gaps.md):settleover a tuple was 25× slower than the same loop as a recursion (collatz), and an index computed fromp div nandp % nin every element keepsfloydat 2.9× C. - The 0.4.0 corpus, text:
levenshtein,kmp,utf8,aho(Aho-Corasick),diff(Myers),trieandwordfreq, in Mimic, C and Rust with the same algorithms, checked against Python. Work that splits into independent pieces runs close to C on all cores (kmp1.07×), while one byte or cell at a time stays 22–36× on one core. - The 0.4.0 corpus, numbers and simulations:
sieve,montecarlo,blackscholes,heat,life,fft,kmeansandbigmul, in Mimic, C and Rust with the same algorithms, checked against Python (numpy, or its own big integers). Arithmetic over independent elements is at or near C on one core (montecarlo1.0×,blackscholes1.18×,kmeans0.84×) and several times faster on all cores. Writing them found four gaps (docs/gaps.md): a record used inside¨is retained and released for every element (20× the CPU time on all cores),puton[u8]copies,math::piwithout()passes the checker, and an FFT built from¨stages is 6× C. - The 0.4.0 corpus, graphs:
bfs,components,topoandpagerank, in Mimic, C and Rust with the same algorithms, checked against Python. Writing them found two more ways an update is copied instead of made in place (docs/gaps.md): anifinside{ … with … }(118 s against 7 s) and a helper that changes an array its caller's record holds. - The 0.4.0 corpus, interpreters and regex:
regex(a Thompson NFA engine, checked against Python'sre),brainf(a Brainf**k interpreter) andvm(a stack bytecode VM), in Mimic, C and Rust. An interpreter's loop is 27–54× C today (docs/gaps.md). - The speed gate:
bench/run.py --gate BEFOREbuilds every benchmark with the changed compiler and with the one it changes, times them in turns on the same machine, and fails on a slowdown beyond that benchmark's tolerance (twice its noise measured on GitHub's machines, 3–25%, frombench/noise/) in 2 of 3 measurements. The bench workflow runs it on release pull requests, nightly ondev, and on pull requests that change what is measured, and checks each time that the compiler without its optimizer (MIMIC_DEBUG_DISABLE=optimizer) fails it. - The 0.4.0 corpus, hashing:
crc32,adler32,fnv1a,murmur3,xxhash32andsha256benchmarks in Mimic, C and Rust, checked against independent references. They show sequential passes over arrays 13–57× slower than C and SHA-256 170× (docs/gaps.md, with the 0.4 steps that fix them), and that Mimic has nofold. - The 0.4.0 corpus, parsing:
csv,expr,tokenize,urlandhttp_parse, checked against Python'scsv,eval,reandurllib. Parsing that splits into independent pieces runs in parallel and is at or near C's time on all cores (csv0.90×,expr0.95×); scanning characters one at a time is 25× C on one core (docs/gaps.md). - The 0.4.0 corpus, compression:
rle,base64andlz77, checked against Python (base64, and reference implementations). They show where growing a list in a loop copies it: the LZ77 decoder is 476× C (docs/gaps.md).rlefoundflattenquadratic (fixed above).huffmanandbwtfollow:huffmanshowed asettlestep written as a lambda copying its state where a named step function changes it in place (37 s against 2.1 s). - The share of the machine:
bench/machine/measures the peak floating-point rate and the memory bandwidth, on one core and on all, and benchmarks that declare their work (meta.json: matmul, mandelbrot, prefix_sum so far) also show what share of that limit each version reached (bench/run.py --machinemeasures again). bench/run.py --jsonwrites a run's times as JSON, and--noise Nruns everything N times unchanged and records how much each ratio to C varies on the machine (bench/noise/<platform>.json; the bench workflow'snoiseinput runs it on GitHub's machines). It is the first part of 0.4.0: the speed gate's tolerances come from this measured noise.
Fixed
sort_indexon integers is several times faster: it boxed every key and compared pairs through the generic comparison; integers (and bytes) are now merged as (key, index) pairs in place, still stable. 2,000,000 keys took about 6 s and now take about 0.7 s, whichgraph::bfs,graph::topoandgraph::mstlean on.concatkeeps a list's kind, andpushcopies in one go:concatof two lists of the same kind of number gave a list of unknown type to the compiler, so every read of the result went the generic way: 5,000,000 reads of aconcatresult took 2.8 s, 0.02 s now (ChaCha20's block state, built byconcat: 9.3 s on one core, 3.1 s now). Andpushonto a list still in use copied it one boxed element at a time; it copies the elements in one go now (Catalan numbers by convolution, keeping the list in a local while it grows: 15 s, 2.3 s now).- A filter whose mask calls a function runs in parallel:
xs ⌿ (xs ¨ prime)was fused into one loop that computed the mask twice (to count, then to fill) on one core; 300,000 Miller-Rabin tests took 1.2 s that way and 0.08 s as a map. Such a filter now builds its mask with¨, in parallel; filters on plain arithmetic (xs ⌿ (xs > 0)) stay fused. pushonto bytes grows them in place: pushing a number onto a[u8]list copied the whole list every time (the number did not match the list's kind), so writing bytes one at a time was quadratic: 100,000 pushes took 0.63 s, and LEB128-encoding 4,000,000 numbers did not finish in 10 minutes. A byte pushed onto bytes held once now grows them in place (2 ms for 100,000); a value that is not a byte still turns them into a list of integers, as before.trailandgatherover numbers give numbers:xs ▷ trail(+)(and×,⌈,⌊, andgatherwith them) over a list ofi64orf64was a list of unknown type to the compiler, so every read of the result went through the generic path. A 256-entry table built bytrail(+)took 3 s to look up 8 million pixels; it takes 0.03 s now. The running results of an empty list off64are an empty list off64.evolveandsettlewith functions by name step in place:evolve(n, step)andsettle(step, done)with named functions called them as function values, which cannot take the state over, so a list in the state was copied at every step: a Bloom filter setting 7,000,000 cells of an 8 MiB list ran for over 15 minutes, andsettlewith a nameddonecopied even when the step was a lambda. They are now the same ass => step(s)ands => done(s): the Bloom filter takes 0.24 s.- A map whose first element is cheap still runs on all cores:
¨over up to 16,384 elements that each may be much work (they reach recursion) timed the first element alone and stayed on one core when it was quick. N-queens counted over its 225 first-two-row starts ran on one core because the first start, both queens in one column, costs nothing. It now times 1, 2, 4, 8, … elements and shares out the rest once that is worth waking the threads: 15 queens 4.55 s → 0.53 s on all cores. andandordecide before running their right side, whatever the types: where a side's type was known only when the program ran (a parameter without a type, a list fromflatten), both sides ran first, soj == ≢ xs or xs[j] > 0stopped the program reading past the end. The right side now runs only when it decides, as with known truth values; lists still go element by element. Found by a merge sort written for the corpus.flattenis fast for small lists too: making it linear (for many lists) made it slower on few small ones, each a parallel map, a running sum and a replicate:utf8, which flattens each character's bytes, ran 7.4 s on one core where 0.3.18 took 5.1 s. Lists that all hold one plain type (numbers, bytes, booleans) are now joined in one copy each:utf84.1 s (0.58 s on all cores),rle1.8 s (5.4 s before). Found by the speed gate comparing preview.2 with 0.3.18.- The README of a new project (
mimic create) links to https://mimic.codes, not the old repository address. - A record passed along a recursion is borrowed: a function that only handed a record on to its own recursive call took it over, so every call from outside retained and released it. Called from every element of a
¨, all cores wrote the same reference count:kmeanswith its centres in a record took 11 s on all cores (89 CPU-seconds), now 1.5 s (3.3), the same as with the lists taken out. puton a list of bytes is in place: an integer put into a[u8](or any value whose type differs from the list's) copied the whole list every time, even when nothing else held it. Thesievebenchmark with byte flags, as C keeps them: 2.9 s on one core (3.6 s with[i64]flags, over 2 minutes with bytes before) and 0.35 s on all cores.- Builds running at once could fail with
redefinition of 'MIM_UI_JS': each rewrote the runtime's cached sources while others compiled from them, and the C compiler, which tells files apart by inode, could take one file for another once an inode was reused. The sources of each runtime version are now written once, into a directory moved into place whole. --previewpicks only a release with files: the releases feed it reads also lists a tag whose release is still being built, so during the minutes a preview was building,mimic upgrade --previewchose it and failed with a 404. It now takes the newest preview or stable release whose files are there.- No release without its files: a release is now published only after its binaries and checksums are uploaded. Before, for a moment a new release could be the latest with nothing to download, and the install command failed with "Not Found" (the install scripts' check on the 0.3.18 release did). That check now runs when the release workflow finishes; it never ran on a release before.
- Builds at the same time no longer spoil the runtime: files Mimic writes "atomically" (through a temporary file) used a temporary name per process, so two threads of one build writing the same runtime file shared it and could interleave their bytes; CI saw
redefinition of 'MIM_UI_JS'once. Every write now has a temporary name of its own, the runtime's object file too. flattenis linear: it joined the lists two at a time, copying the growing result again for every list, so flattening many small lists was quadratic (200,000 pairs: about a minute; now milliseconds). Each element is now placed once, in parallel. The same in theuimodule. Found by the 0.4.0 benchmark corpus.
Install
Download the file for your system below and unpack it. Then run the install script inside: it copies mimic to ~/.mimic/bin, puts that folder on your PATH, and checks what your system needs.
| System | File | Install | Also needed |
|---|---|---|---|
| Windows x86_64 (10, 11) | mimic-0.4.0-windows-x86_64.zip |
Double-click install.cmd |
Nothing: Windows programs are linked with the MinGW-w64 inside mimic. |
| macOS Apple silicon | mimic-0.4.0-macos-arm64.tar.gz |
./install.sh |
The Xcode Command Line Tools (xcode-select --install), for the macOS SDK. |
| Linux x86_64 | mimic-0.4.0-linux-x86_64.tar.gz |
./install.sh |
glibc 2.28 or newer (Ubuntu 20.04, Debian 10, RHEL 8 or later) and a C compiler (cc) to link native programs. --target x86_64-linux needs nothing else. |
On Windows, if double-clicking install.cmd does nothing (some company PCs block scripts), open PowerShell in the unpacked folder and run:
powershell -NoProfile -ExecutionPolicy Bypass -File ".\install.ps1"The script says if something is missing and how to install it. Open a new terminal afterwards so the new PATH applies.
Upgrading from an earlier Mimic: run the new install script the same way. It replaces the old mimic, clears the build cache the old version left in ~/.mimic/cache (it is rebuilt on first use), and keeps your projects and installed libraries. If another mimic comes first on your PATH, it says where, and offers to remove it.
- macOS: the script clears the download quarantine. If you copy
mimicby hand instead, runxattr -d com.apple.quarantine mimiconce. - Windows: the script unblocks the downloaded files. SmartScreen may still ask the first time: "More info" → "Run anyway".
- Uninstall:
./install.sh --uninstall, orinstall.cmd -Uninstallon Windows. Your projects are not touched.
First program
mimic create hello
cd hello
mimic runmimic --help lists every command. SHA256SUMS has the checksum of each file.