New submission from Serhiy Storchaka <storchaka+cpyt...@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 <rep...@bugs.python.org> <https://bugs.python.org/issue38639> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com