New submission from Stefan Behnel <stefan...@behnel.de>:

Spelling out the numerator/denominator calculation in the __mod__ special 
method, and actually implementing __divmod__, speeds up both operations by 
2-3x. This is due to avoiding repeated Fraction instantiation and 
normalisation, as well as less arithmetic operations.

$ ./python -m timeit -s 'from fractions import Fraction as F; a = F(-7, 3); b = 
F(3, 2)' 'a%b'
50000 loops, best of 5: 9.53 usec per loop
$ ./python -m timeit -s 'from fractions import Fraction as F; a = F(-7, 3); b = 
F(3, 2)' 'a%3'
50000 loops, best of 5: 6.61 usec per loop
$ ./python -m timeit -s 'from fractions import Fraction as F; a = F(-7, 3); b = 
F(3, 2)' 'divmod(a, b)'
20000 loops, best of 5: 14.1 usec per loop
$ ./python -m timeit -s 'from fractions import Fraction as F; a = F(-7, 3); b = 
F(3, 2)' 'divmod(a, 3)'
20000 loops, best of 5: 10.2 usec per loop

$ ./python -m timeit -s 'from fractions import Fraction as F; a = F(-7, 3); b = 
F(3, 2)' 'a%b'          
100000 loops, best of 5: 2.96 usec per loop
$ ./python -m timeit -s 'from fractions import Fraction as F; a = F(-7, 3); b = 
F(3, 2)' 'a%3'
100000 loops, best of 5: 2.78 usec per loop
$ ./python -m timeit -s 'from fractions import Fraction as F; a = F(-7, 3); b = 
F(3, 2)' 'divmod(a, b)'
100000 loops, best of 5: 3.93 usec per loop
$ ./python -m timeit -s 'from fractions import Fraction as F; a = F(-7, 3); b = 
F(3, 2)' 'divmod(a, 3)'
50000 loops, best of 5: 3.82 usec per loop

----------
components: Library (Lib)
messages: 332533
nosy: scoder
priority: normal
severity: normal
status: open
title: Speed up mod/divmod for Fraction type
type: performance
versions: Python 3.8

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue35588>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to