gh-93325: Micro-optimization of small integer lookup#93326
Conversation
|
Thanks for the PR. How repeatable are those timings? A 6% speed up would be impressive, but it's well within the margin of error, and seems surprisingly large for what should be removal of a single assembly instruction (and possibly not even that - on Intel hardware, we could just be replacing an LEA instruction with an addition, keeping the total number of instructions the same). As an experiment, I've been running your script in a loop, alternating between commit b8135e9 on this branch and commit dec1e93 on main. This is on macOS / Intel, with both branches configured and built with |
|
Looking at the assembly on my machine, I do see a difference: here's what I typically see for the lookup on main (not surprisingly, And here's the corresponding code in this branch: |
|
Conclusion: I'm not yet seeing any evidence that this micro-optimization is actually an optimization. :-) @markshannon Any thoughts on this PR? |
|
This is going to be slower. It replaces an add with a load, which is almost always going to be slower, and never faster. |
|
In many situations, compilers may be able to constant-fold |
|
@mdickinson @markshannon @sweeneyde Thanks for the responses. I did some more testing. The timings reported above are repeatable, but have been taken on a Windows system with the default build from the Visual Studio build files. I repeated the experiments, but now with binaries generated with the command I am still amazed that the compiler can handle this, but the numbers show no speedup so I will close this PR. |


The small integers are accessed through
_PyLong_SMALL_INTS. This requires adding the constant_PY_NSMALLNEGINTSto the integer desired. This PR adds a new global variable_PyLong_SMALL_INTS_ZERO_OFFSETthat points to the zero integer.Advantages:
get_small_int,_PyLong_GetZero,_PyLong_GetOnerequire an addition operation less._PyLong_GetZeroand_PyLong_GetOneare inline functions, less code is generatedBenchmark:
Test script
Notes:
small_ints_zero_offset. This extra global can be avoided if we: first allocatesmall_ints, then add_PY_NSMALLNEGINTSto the pointer. For deallocating one first has to substract_PY_NSMALLNEGINTSagain. This is a little more complex, but if preferred I will adapt the PR to this.small_ints_zero_offsetpointer. Suggestions for improvement are welcome.Fixes #93325.