bpo-44547: Make Fractions objects instances of typing.SupportsInt by mdickinson · Pull Request #27851 · python/cpython (original) (raw)

No idea, but I wouldn't expect it to be significant in either direction

Hmm; I was wrong. I do see a significant difference in casual timings, apparently arising from the slowness of the 'int' call.

On this branch:

lovelace:cpython mdickinson$ ./python.exe -m timeit -s "from fractions import Fraction; f = Fraction(1001, 65)" "int(f)"
2000000 loops, best of 5: 193 nsec per loop

On the main branch:

lovelace:cpython mdickinson$ ./python.exe -m timeit -s "from fractions import Fraction; f = Fraction(1001, 65)" "int(f)"
2000000 loops, best of 5: 166 nsec per loop

Using operator.index is faster here: if I use

    def __int__(a, _index=operator.index):
        """int(a)"""
        if a._numerator < 0:
            return _index(-(-a._numerator // a._denominator))
        else:
            return _index(a._numerator // a._denominator)

I get something that's consistently faster than either of the above:

lovelace:cpython mdickinson$ ./python.exe -m timeit -s "from fractions import Fraction; f = Fraction(1001, 65)" "int(f)"
2000000 loops, best of 5: 156 nsec per loop