Skip to content

Strings

A 200,000-line log built with f-strings, then split, parsed, counted by path in HashMap[str, float], ordered in a TreeMap, and run-length encoded one character at a time, all with native str. Every function goes native, and the program prints the same thing on all three paths.

Run it

python  text.ppy
ppy run text.ppy
ppy build --standalone text.ppy -o dist && ./dist/text

What it prints

python text.ppy, ppy run text.ppy, ppy build --standalone text.ppy -o dist && ./dist/text

/api/orders        451.74 ms  x40,000
/api/search        448.74 ms  x40,000
/api/users         447.74 ms  x40,000
/health            449.73 ms  x40,000
/static/app.js     450.75 ms  x40,000
levels: INFO=50000 DEBUG=50000 ERROR=50000 WARN=50000
a3b1c2d5 46075322

What it does

  • make_log writes each line with an f-string: a zero-padded day, a level padded to five with :<5, a path, a time with :.2f, and a user id.
  • slowest_paths splits each line on whitespace, strips took= and ms with removeprefix and removesuffix, reads the number with float(), and sums per path in a HashMap[str, float]. The report walks the paths in order through a TreeMap[str, float] and formats each with :<16, :>9.2f, and :,.
  • levels slices the level out of each line (line[11:16].strip()) and counts them.
  • compress walks a string with for c in s, comparing one character with the last, and builds the encoding with +=.
  • checksum uppercases each line, encodes it, and folds ord of each character of the result.

report calls them all and returns one string. It is marked @ppy.native: it has no loop of its own, and without the mark the compiler would judge its body too small to be worth the Python boundary, though the functions it calls do all the work.

How it runs natively

A string is a counted handle into the C runtime in ppy_runtime/strings.c, holding its UTF-8 bytes, its length in code points, and whether it is ASCII. The line list is a Vec[str]; a map keyed by str hashes and compares the text.

Two things keep allocation down, as CPython does the same two:

  • the 128 one-character ASCII strings are static, so for c in text and text[0] allocate nothing
  • out += part appends in place when nothing else holds out

ppy explain text.compress and the others each say llvm backend: native.

Timing

Wall time for the whole program, the mean of five runs, measured from a checkout under /tmp on one machine (Python 3.14, an Intel Core Ultra 9 386H under WSL2):

seconds
python text.ppy 1.87
idiomatic.py: the same work with str, dict, Counter, defaultdict, and sorted 1.67
ppy run text.ppy, after the first run built the cache 0.53
./dist/text, the standalone binary 0.49

Measured inside the process, report itself takes 0.48 seconds under ppy run and 1.82 under CPython; the rest of ppy run's time is starting the interpreter and loading the cached native code. Under CPython, text.ppy runs its Vec and HashMap as the reference classes in Python, which is why it trails idiomatic.py.

Where the code comes from

text.ppy and idiomatic.py are hand-written.

Read on: the strings guide.

48_strings/text.ppy

"""Text processing with native strings: a log parsed, counted, and reported."""

import ppy
from ppy import HashMap, TreeMap, Vec

LINES = 200000


def make_log(count: int) -> Vec[str]:
    names = ["INFO", "WARN", "ERROR", "DEBUG"]
    paths = ["/api/users", "/api/orders", "/static/app.js", "/health", "/api/search"]
    lines = Vec[str]()
    for i in range(count):
        level = names[(i * 7) % 4]
        path = paths[(i * 13) % 5]
        took = (i * 37) % 900 + 0.25
        lines.push(f"2026-09-{i % 28 + 1:02d} {level:<5} {path} took={took:.2f}ms user=u{i % 997}")
    return lines


def slowest_paths(lines: Vec[str]) -> str:
    total = HashMap[str, float]()
    count = HashMap[str, int]()
    for line in lines:
        fields = line.split()
        path = fields[2]
        took = float(fields[3].removeprefix("took=").removesuffix("ms"))
        total[path] = total.get(path, 0.0) + took
        count[path] = count.get(path, 0) + 1
    order = TreeMap[str, float]()
    for path in total:
        order[path] = total[path] / count[path]
    shown = ""
    for path in order:
        shown += f"{path:<16}{order[path]:>9.2f} ms  x{count[path]:,}\n"
    return shown.rstrip()


def levels(lines: Vec[str]) -> str:
    seen = HashMap[str, int]()
    for line in lines:
        level = line[11:16].strip()
        seen[level] = seen.get(level, 0) + 1
    parts = Vec[str]()
    for level in seen:
        parts.push(f"{level}={seen[level]}")
    return " ".join(["levels:", parts[0], parts[1], parts[2], parts[3]])


def compress(text: str) -> str:
    """Run-length encoding, one character at a time: `aaab` is `a3b1`."""
    if not text:
        return ""
    out = ""
    last = text[0]
    run = 0
    for c in text:
        if c == last:
            run += 1
        else:
            out += last + str(run)
            last = c
            run = 1
    return out + last + str(run)


def checksum(lines: Vec[str]) -> int:
    total = 0
    for line in lines:
        packed = compress(line.upper())
        for c in packed:
            total = (total * 31 + ord(c)) % 1000000007
    return total


@ppy.native
def report(count: int) -> str:
    lines = make_log(count)
    return f"{slowest_paths(lines)}\n{levels(lines)}\n{compress('aaabccddddd')} {checksum(lines)}"


def main() -> None:
    print(report(LINES))


main()

Source: examples/48_strings.