[New-bugs-announce] [issue38639] Optimize floor() and ceil() for floats

Serhiy Storchaka report at bugs.python.org
Wed Oct 30 05:29:36 EDT 2019


New submission from Serhiy Storchaka <storchaka+cpython at gmail.com>:

Currently math.floor(), math.ceil() and math.trunc() look up special methods __floor__, __ceil__ and __trunc__ correspondingly and execute them if found. Otherwise they execute common code for floats. There are no special slots for these methods, so looking up these names in type dicts takes some time. It is a waste of time for most common case -- float objects.

The proposed PR adds checks PyFloat_CheckExact() before looking up the special method. Some microbenchmarks:

$ ./python -m pyperf timeit -s "from math import floor" --duplicate 100 "floor(12345.6)"
Before:  Mean +- std dev: 63.2 ns +- 1.7 ns
After:   Mean +- std dev: 51.8 ns +- 1.3 ns

$ ./python -m pyperf timeit -s "from math import ceil" --duplicate 100 "ceil(12345.6)"
Before:  Mean +- std dev: 61.1 ns +- 1.5 ns
After:   Mean +- std dev: 51.9 ns +- 1.1 ns

$ ./python -m pyperf timeit -s "from math import trunc" --duplicate 100 "trunc(12345.6)"
Before:  Mean +- std dev: 72.0 ns +- 1.5 ns
After:   Mean +- std dev: 34.7 ns +- 1.4 ns

We should also check how this optimization affects other types:

$ ./python -m pyperf timeit -s "from math import floor" --duplicate 100 "floor(12345)"
Before:  Mean +- std dev: 56.3 ns +- 1.3 ns
After:   Mean +- std dev: 56.3 ns +- 1.4 ns

$ ./python -m pyperf timeit -s "from math import ceil" --duplicate 100 "ceil(12345)"
Before:  Mean +- std dev: 55.7 ns +- 1.6 ns
After:   Mean +- std dev: 56.8 ns +- 1.6 ns

$ ./python -m pyperf timeit -s "from math import trunc" --duplicate 100 "trunc(12345)"
Before:  Mean +- std dev: 54.7 ns +- 1.3 ns
After:   Mean +- std dev: 56.7 ns +- 1.5 ns

----------
components: Interpreter Core
messages: 355699
nosy: mark.dickinson, serhiy.storchaka
priority: normal
severity: normal
status: open
title: Optimize floor() and ceil() for floats
type: performance
versions: Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue38639>
_______________________________________


More information about the New-bugs-announce mailing list