[New-bugs-announce] [issue22486] Speed up fractions.gcd()
report at bugs.python.org
Wed Sep 24 22:40:35 CEST 2014
New submission from Stefan Behnel:
fractions.gcd() is required for normalising numerator and denominator of the Fraction data type. Some speed improvements were applied to Fraction in issue 22464, now the gcd() function takes up about half of the instantiation time in the benchmark in issue 22458, which makes it quite a heavy part of the overall Fraction computation time.
The current implementation is
def gcd(a, b):
a, b = b, a%b
Reimplementing it in C would provide for much faster calculations. Here is a Cython version that simply drops the calculation loop into C as soon as the numbers are small enough to fit into a C long long int:
def _gcd(a, b):
# Try doing all computation in C space. If the numbers are too large
# at the beginning, retry until they are small enough.
cdef long long ai, bi
ai, bi = a, b
# switch to C loop
ai, bi = bi, ai%bi
a, b = b, a%b
It's substantially faster already because the values will either be small enough right from the start or quickly become so after a few iterations with Python objects.
Further improvements should be possible with a dedicated PyLong implementation based on Lehmer's GCD algorithm:
components: Library (Lib)
title: Speed up fractions.gcd()
versions: Python 3.5
Python tracker <report at bugs.python.org>
More information about the New-bugs-announce