Skip to content

Conversation

remyoudompheng
Copy link
Contributor

@remyoudompheng remyoudompheng commented Sep 7, 2025

This is a proposal to handle issue #159 for Python versions below 3.14 (for example Ubuntu 24.04 LTS uses Python 3.12).
The idea is to use standard int methods (from_bytes, to_bytes) to obtain a binary serialization, then cast the byte array to ulong.

Special care is needed for big-endian platforms, however I am unable to test whether the patch proposal is correct for big-endian platforms. Let me know what would be the preferred approach.

Benchmarks done using %timeit in iPython with Python 3.13
AFAIK gmpy2 uses private Python stuff already so it might be difficult to do better.

Number gmpy2 int(mpz) gmpy2 mpz(int) int(fmpz) 0.8.0 fmpz(int) 0.8.0 int(fmpz) PR fmpz(int) PR
3^100 45.7 ns 53.6 ns 186 ns 234 ns 138 ns 166 ns
3^10000 1.49 µs 1.23 µs 6.63 µs 6.52 µs 1.15 µs 1.06 µs
-3^10000 1.50 µs 1.23 µs 6.63 µs 6.60 µs 1.24 µs 1.23 µs

(edited for changes in commit f349183 for negative numbers)

@remyoudompheng
Copy link
Contributor Author

The function ulong_from_little_endian is endian-agnostic and was tested by forcing is_big_endian=1 on a little-endian system.

@remyoudompheng
Copy link
Contributor Author

remyoudompheng commented Sep 7, 2025

Since this PR seems to give performance on par with gmpy2 it is unclear whether PEP 757 will be even necessary. I have not been able to build #64 for comparison

Also, it should work with older Python versions.

@oscarbenjamin
Copy link
Collaborator

The PEP 757 interface is provided as CPython's best effort to give something efficient for this using public API in Python 3.14 onwards. I think that should be the baseline before trying any other approach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants