Repository navigation
perf: close everyday-library gaps to CPython - #112
Draft
owenthcarey wants to merge 746 commits into
Draft
owenthcarey wants to merge 746 commits into
owenthcarey wants to merge 746 commits into
Conversation
…exdigest as leaf halves and SHA-256/384/512 on ring; partial calls try the remembered slot layout before the thread-local names
…es (zlib, bz2, lzma, zstd and hashlib leaked every one)
…t__ and the receiver, with no bound method; memoryview methods are shared per name
…he UTF-16/UTF-32 and escape encoders, the wchar_t copies and the path converters (charset_normalizer 3.5.3 calls PyUnicode_DecodeUTF32)
…k to the frame JIT; obj in set/dict finds identity-hashed instances natively; instance deaths skip the native-state scan by a class bit
… building no tuple and calling no builtin (a frozen dataclass's __hash__, dict and set lookups on such keys)
… (a call that built the list no longer keeps a loop of set lookups in tier 2)
…te's entry names one, on the instance, class and entry already loaded (about 38 instructions a read)
…stances' classes in one operation, building no class objects (a dataclass's __eq__)
…binds them in order; its scratch vector and builtin buffer are made only where used
…th the instance (in place for native arguments), and a site reading e.args or another pseudo-slot reads it first
…uences, a list of exact tuples), and tier 2 steps a dict's int keys or values in the scalar lane
…ng (the shortest first only for a short mantissa), and a number's format spec computes no str first
…llocate none), and a compiled bytes.join of a list or tuple calls the native body
…guarded by the class version), and tier 2 counts such a subscript as a dynamic Python call
…hon call, so a loop counting a < b of instances runs in the frame JIT
… its slots, as the end operations do
…ember's place (a setter shared by several classes stays in compiled code), and an in-line __getitem__ whose guard fails calls the method directly
…ore drains filter(None, ...) over a plain sequence in place
…ires at its end in compiled code, as a plain cursor does
…ore its verdict (a declined property store no longer pays it; richards back to level) and records the site's slot shortcut; the nested-closure compile timing test takes the best of seven with more slack
…the in-tree pip upgraded it to 26.4 while installing pytest and the 26.3 suite no longer imported
…binding is memoized per site, and to_bytes, from_bytes, rsplit and splitlines have halves; a list releases its items last first, and to_bytes/from_bytes reject a positional signed and unknown keywords
… and a string's or container's recorded miss in the leaf; int.bit_count, bytes.find and bytes.hex are leaves, and b.hex(sep) writes a one-byte separator directly
…'s leaf, and its switch to the float loop adds the float directly
…keys natively; SimpleNamespace(k=v) builds from the keyword names; d.update(k=v) stores them through the leaf insert
…string's list for its fields
…ethods are leaves; tier 2 keeps a global object's pin for the rest of its run
…-half method, pop(i) and leaf bodies through the native method site; a short list's sort skips the run stack
…e and changes each match in place; dict(d, k=v) of an exact dict copies its table once and puts the keywords in natively; sorted(xs, key=d.__getitem__ or d.get) reads every key under one view of the table; list(islice(src, stop)) over a source that runs no code drains in one pass; fix: a dict subclass that keeps dict's __iter__ merges from its table, whatever its own keys and __getitem__, as CPython's dict_merge reads it
…28 bits runs natively; bytes.split of one byte cuts between memchr matches into a presized list; tuple sort keys compare string and integer elements directly; itemgetter of two or three items builds its tuple from a fixed array
… before binding it; obj.__dict__ remembers its managed-dict verdict per class version; xs[a:b] = ys with literal bounds splices in the leaf arms; list slices and starred unpacking copy items in bulk; json.loads files keys under their own cached string hash
…ters in place, as the frame JIT does; a fresh instance's field read whose release is its last takes the field cache before the slow helper's other checks; array subscripts and len() borrow the buffer; OrderedDict.move_to_end renumbers a long run in one pass over the slots; fix: the stack attribute helper's early answers run a finalizer the receiver's release queued before the next instruction
…re-leaf hashes in place; fix: a dict subclass's __missing__ globals stop gating builtin lookups once no function or frame holds the dict, even inside a cycle, so a pure __hash__ defined before a typing.NamedTuple keeps its leaf verdict
… built-in names and modes static, and skip the destructor's flush and descriptor work when nothing is staged; math.gcd and math.lcm of machine words stay in 64-bit words; fix: os.fdopen(fd).name is the descriptor, as open(fd) reports it
… 1-D memoryview items read in place; UTF-16/32 encodes take the leaf encoder; constant-bound str slices cut in the compiled subscript helper; isinstance/issubclass call a plain-function metaclass hook directly; fix: iter_unpack over a bytearray holds an export until the iteration ends
…check from lazily filled per-form bitsets and return already-normalized input as is; NFD skips the database below U+00A0; typed lru_cache wrappers probe up to four positional arguments and their classes natively
…etitem__) bind in place instead of making the frame real; map(d.__getitem__, xs) probes the dict natively per item; bytes.startswith/endswith take a tuple of bytes in the leaf half and stop copying candidates; str.expandtabs skips the argument copy and presizes its output
…tertools object stays in compiled code (the read binds the kind's memoized method and the site's slot keeps the type's native method); floor division and modulo of machine ints with negative operands run in leaf plans and the interpreter's leaf path, so sort keys like lambda x: (-x % 3, x) stay pure; bounded deques skip copying the items a long source would trim; short format specs parse from a stack buffer; fix: the % format type's width counts the percent sign
…e (cycle and other itertools objects too); bytes(range(...)) fills directly; islice presizes its output; a for loop over a tuple of fresh lists or tuples of plain scalars frees them quietly; str.join and bytes.join of a native iterator join in place; ''.join skips the separator; bytearray.hex() reads the buffer in place
…oad and order, and OrderedDict.fromkeys builds through it; list(od), the native constructor's __init__ check and list()'s deque test are remembered per class version; a native constructor's parameters named as keywords build natively (deque(xs, maxlen=5)); math.isclose of two plain numbers at the default tolerances compares at once
…a list, tuple or range cursor calls that half per item and steps the cursor in place; str.lower()/upper() of ASCII text with nothing to change return the string itself; a generator resting in yield from a list, tuple or range cursor, drained by sum/any/all/list/set.update, hands up to 256 items at a time straight to the consumer (only when its own frame is the drained one, not a generator the drained one resumed lazily); set(xs) steps a cursor in place; an instance's hash tests for Enum.__hash__ only after finding the class's memoized __hash__
…built ((self.x, self.y) < (o.x, o.y), dataclass(order=True)'s methods) compares the items without building either: the first tuple's op is dropped, the straight-line ops between move up past its items' registers, and the second becomes one ItemsCompare op that settles unequal leading ints in line
…n place (the sift's comparisons dry-run first, ints, floats, str and tuples of them); a leaf plan comparing two fresh list literals of one to three items fuses like the tuple form; x in seq, seq.count(x) and seq.index(x) of an instance with a short pure __eq__ resolve it once and call it per member of its class; os.DirEntry attributes live in the class's shared layout, laid down at once, and scandir joins the directory to the validated name instead of building, validating and copying a path
…it enters a function (the instance allocated and bound as self, handed back in one step when __init__ returns None), exception classes with a Python __init__ included (args seeded at allocation, super().__init__(msg) storing them in place); __init__ storing through a data descriptor is settled as no store-only build and a declining leaf loses its verdict; direct entries take *args callees; a __new__ that only returns object.__new__(cls) (after an optional cls reassignment) is skipped; an entry declined after allocation puts the call back
… stores through the same caches when the frame has no namespace of its own); a store-only constructor is built from compiled code's class dispatch; a framed __init__'s instance has room for its class's names, a container stored into an untracked instance tracks it in line (straight into the young set); a loop tier 2 carves out for an opcode it never compiles (with's LOAD_SPECIAL) goes to the frame JIT at its first trigger, even when tier 2 compiled the function's other loops
…g (None through str), not only numbers; a loop of a function large enough that tier 2 waits for its whole body's budget goes to the frame JIT at the first trigger; a generator resting in a yield from whose delegate is itself in one collapses the chain instead of resuming level by level (await chains keep the three-deep lazy resume)
…ts in their bodies (missed += 1), checked at run time; a subscript miss or a division by zero under pending values raises in compiled code instead of leaving for the core loop to redo it; d.pop(k)'s native half raises the KeyError of a missing key; WITH_EXCEPT_START warms a pure __exit__ with no native body; tier 2 declines a store whose value never got a type instead of panicking in lowering
…s locals (a slot-to-cell index built with the code's constants, where it searched the cell list for each local); a blind except clause with no arithmetic in its body keeps the moves-only check, the arithmetic one running out of line
…rength.REQUIRED) is one helper call that lands the constant the attribute site's stamp holds for that class at its version; when the stamp doesn't hold, the helper pushes the global's value and the attribute read runs as before
…short when tier 2 measures it, and code whose loops ran 16 iterations or fewer a call skips tier 2's framed entry in the core loop too (the frame JIT puts such callees in line); tier 2's element-step rule doesn't count a small pure leaf's call as typed work; polymorphic split-field reads have helpers of their own that pick the position by class version among the site's entries and its code's field slot
…that compiled code calls in place, reading the entry's cached kind and inode off its split fields; a followed link's kind comes from the entry's cached stat() result, as CPython's does, rather than a fresh fstatat per call
…ilds, blocks start with room for eight instructions, and lowering reserves IR room for inlined callees; an inlined fused global-and-attribute read keeps its attribute site's stamp slot as an address; tier 2's short-loop test switch reads as one expression for clippy
…probe, getattr, setattr) find the entry by the name's cached hash, whose filter answers a never-set name at once; a dunder class read classifies its name once; a type-cache miss walks the MRO through guard-free views; a lock's state is read off its first slot without a key compare
…er before the slot and field lanes; a slot member a site saw unset at the class's version raises at once; a registered callee returning with a lean shell retires it in place; a builtin receiver's attribute miss asks the builtin table first
…e reads in line; cls(*args) of a natively served class builds in place; a slot member proved unset raises without a second lookup, counting only members unset in the laid-out block; the interpreter's attribute site skips resolution for a cached property getter and caches a Python class method read off its class; iterating a class with a Python __iter__ skips the OrderedDict lookup
…h CPython's semantics (type name, sentinel-first compare, StopIteration from the callable, re-entrant exhaustion, reduce through the current builtins' iter) whose steps call a Python callable through the pure-callback lane; a dotted attrgetter walks its parts in place
…y compiled code; natively loaded modules' specs carry _initializing = False as CPython's do, so module dunder reads stay in a callee's leaf half; the import audit event fires only when a module is loaded, so cached lanes no longer decline under an audit hook; a relative __import__ with non-dict globals raises TypeError
…ribute__ first; closing an os.scandir iterator drops its entries and leaves its finalizer nothing to do, so with-scandir loops stay compiled and step the iterator in place; enumerate over a two-cursor zip builds each pair fresh for the unpacking to take apart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR works through the places where WeavePy still trails CPython 3.14, starting with the everyday-operations battery (
tools/pybench/everyday.py), where it trailed the most. It's a draft while the work continues; each commit is a self-contained step.So far
The battery's geometric mean of instructions retired against CPython went from 1.447 to 1.366 (quick builds, one run per case).
bytes.replaceb[5:20]b"%d:%s" % argsbytes(10)bytearray(b)datetime.astimezone(utc)replace(tzinfo=utc).timestamp()weakref.ref(x)The figures are WeavePy's instructions per operation over CPython's.
bytes. Methods read their receiver in place instead of copying it, short searches skip thememmemset-up, and slicing, indexing,%formatting, and thebytesandbytearrayconstructors get fast paths.datetime.replace,timestamp, andastimezonerun natively for exact classes with notzinfoor a fixed-offsettimezone, following_pydatetime's_mktimeand_local_timezonestep for step. Anything else falls back to the Python methods. Results are identical to the previous build's across DST gaps and folds in five time zones.weakref.ref(x). It's now a pure constructor.Testing
test_compileallandtest_embed, are the known noise.RUST_MIN_STACK=8388608.