Remix.run Logo
stabbles 3 hours ago

`sys.monitoring` is nice. I used it to find inefficiently ordered chains of branches in one of my projects. For example a chain of `if isinstance(foo, ...); elif isinstance(foo, ...); elif isinstance(foo, ...);` can be reordered from most to least popular based on a representative run, to avoid evaluating branch conditions more than necessary. You collect BRANCH_LEFT/BRANCH_RIGHT events, divide the code objects into "basic blocks", build a graph from them with edges weighted by frequency, and identify chains using a simple algorithm [1]. Then report chains where the long jump is taken more often than the short jump. It's like semi-automatic PGO for Python.

[1]: https://dl.acm.org/doi/abs/10.1145/93542.93550