Primer โ€” bit-packed prime sieve (fast + tiny memory, embedded-friendly)

โš“ Rust    ๐Ÿ“… 2026-02-14    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 3      

surdeus

Hi everyone,

Iโ€™m new here and wanted to share a crate I put together called Primer: a prime generator/sieve focused on being both fast and extremely memory efficient (especially on constrained targets like ESP32-class devices).โ€‹

Repo: https://github.com/wisprer/primerโ€‹

What it is

Primer is a bit-packed, odd-only Sieve of Eratosthenes implementation that generates primes in increasing order, with an emphasis on low memory residency and good real-world throughput.โ€‹

Why it might be useful

A lot of prime approaches end up memory-heavy (or require tradeoffs that donโ€™t suit embedded / small-footprint work), so Primer aims for โ€œsmall and sharpโ€: 1 bit per odd candidate, cache-friendly scanning, and fast bit-iteration to skip work.โ€‹

The core tricks used are:

  • Bit packing (1 bit per odd number rather than byte/word-per-number style storage).โ€‹
  • Odd-only sieving (hardcode 2, then only represent/process odd candidates).โ€‹
  • Fast bit scanning using trailing_zeros (which the README notes compiles down to efficient CPU instructions on x86_64).โ€‹
  • Brian Kernighanโ€™s bit-iteration trick (iterate only over set bits rather than scanning all 64 positions).โ€‹

Performance & footprint (from the README)

In the included benchmarks, Primer is reported as about 64ร— faster than the primes crate in certain cases, and can be in the same ballpark as primal depending on the workload.โ€‹

For n = 500,000 (41,538 primes), the READMEโ€™s table lists roughly:

  • Primer: ~4 KB memory, ~2 ms.โ€‹
  • primes crate: ~500 KB memory, ~15 ms.โ€‹
  • primal crate: ~50 KB memory, ~3 ms.โ€‹

The README also includes a scaling table up to 100M with estimated memory/time characteristics (e.g., 10M โ‰ˆ 80 KB, ~15 ms; 100M โ‰ˆ 800 KB, ~200 ms).โ€‹

API / examples

The README includes a simple entry point (sieve_primes(limit) -> Vec<u64>) and shows patterns like generating a prime table once at startup and reusing it for things like hashing/partitioning use cases.โ€‹

Feedback welcome

Iโ€™d love feedback on the approach, API ergonomics, correctness/testing strategy, and benchmark methodology, and Iโ€™m very open to making it more idiomatic or adjusting claims if anyone spots an issue.โ€‹

Thanks for taking a look!

3 posts - 3 participants

Read full topic

๐Ÿท๏ธ Rust_feed