Skip to content

gh-120196: Faster ascii_decode and find_max_char implementations - #120212

Closed
rhpvorderman wants to merge 24 commits into
python:mainfrom
rhpvorderman:MICROOPTIMIZATIONS
Closed

rhpvorderman wants to merge 24 commits into
python:mainfrom
rhpvorderman:MICROOPTIMIZATIONS

Conversation

@rhpvorderman

@rhpvorderman rhpvorderman commented Jun 7, 2024 •

Copy link
Copy Markdown
Contributor

One byte find_max_char. This now follows the following algorithm.

  • Find the start where the first aligned load can take place.
  • Bitwise OR all characters together up to the aligned start and check with ASCII_MASK.
  • At aligned start, start loading size_t units in groups of 4. Bitwise OR together and check with ASCII_MASK.
  • When there are less than 4 * size_t units left, get the remaining size_t units and the remainder of the single char units and bitwise OR them all together.

This methodology has the following advantages:

  • The number of checks is significantly reduced. (Both ASCII_MASK check and loop iterator check).
  • Due to the extremely low cost of a OR operation handling 4x size_t chunks of data is barely more expensive than single size_t s. As a result the penalty for not exiting earlier if a byte larger than 127 is found is minimal.
  • The compiler is able to vectorize the bitwise OR on the 32 KB chunks. Please note that this only works for GCC 14.1 and higher.

Two and four byte find_max_char.

  • Increase the unroll size from 4 to 8. This means loading 16 and 32 bytes simultaneously for Py_UCS2 and Py_UCS4. GCC 14.1 can now vectorize the load and the bitwise OR, which should result in faster speed.

ascii_decode:

  • The same advantages as decribed in find_max_char. This function also performs some copying. Using the restrict qualifier on the pointers allows GCC to do a vector store operation. Unfortunately GCC < 14.1 loads the value once for the bitwise OR and once for the load store. Only the load store is vectorized in GCC < 14.1. Luckily, since both loads are from the same cache line and no other loads are performed in between, the latency this introduces should be near zero.

So from GCC 14.1 onwards the performance should improve. My debian system has GCC 12.2 but that also should give some improvements.

If only I could benchmark: https://discuss.python.org/t/building-python-takes-longer-than-an-hour-due-to-freezing-objects-and-still-counting/55144

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting review performance Performance or resource usage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants