Message222731
Python 2 has fast path in ceval.c for operations (a+b, a-b, etc.) on small integers ("int" type) if the operation does not overflow.
We loose these fast-path in Python 3 when we dropped the int type in favor of the long type.
Antoine Pitrou proposed a fast-path, but only for int singletons (integers in the range [-5; 255]): issue #10044. His patch was rejected because it introduces undefined behaviour.
I propose to reimplemenet Python 2 optimization for long with a single digit, which are the most common numbers.
Pseudo-code for BINARY_ADD:
---
if (PyLong_CheckExact(x) && Py_ABS(Py_SIZE(x)) == 1
&& PyLong_CheckExact(y) && Py_ABS(Py_SIZE(y)) == 1)
{
stwodigits a = ..., b = ...;
stwodigits c;
if (... a+b will not overflow ...) {
c = a + b;
return PyLong_FromLongLong(c);
}
}
/* fall back to PyNumber_Add() */
---
The code can be copied from longobject.c, there are already fast-path for single digit numbers. See for example long_mul():
---
/* fast path for single-digit multiplication */
if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
....
}
---
As any other optimization, it should be proved to be faster with benchmarks. |
|
| Date |
User |
Action |
Args |
| 2014-07-11 09:10:28 | vstinner | set | recipients:
+ vstinner, mark.dickinson |
| 2014-07-11 09:10:27 | vstinner | set | messageid: <[email protected]> |
| 2014-07-11 09:10:27 | vstinner | link | issue21955 messages |
| 2014-07-11 09:10:27 | vstinner | create | |
|