Skip to content

Commit 7463f3a

Browse files
committed
Optimise math.ceil for known exact float
This matches a similar optimisation done for math.floor in #21072 Before: ``` λ ./python.exe -m timeit -r 11 -s 'from math import ceil' -s 'x=3.14' 'ceil(x)' 20000000 loops, best of 11: 13.3 nsec per loop λ ./python.exe -m timeit -r 11 -s 'from math import ceil' -s 'x=0.0' 'ceil(x)' 20000000 loops, best of 11: 13.3 nsec per loop λ ./python.exe -m timeit -r 11 -s 'from math import ceil' -s 'x=-3.14E32' 'ceil(x)' 10000000 loops, best of 11: 35.3 nsec per loop λ ./python.exe -m timeit -r 11 -s 'from math import ceil' -s 'x=-323452345.14' 'ceil(x)' 10000000 loops, best of 11: 21.8 nsec per loop ``` After: ``` λ ./python.exe -m timeit -r 11 -s 'from math import ceil' -s 'x=3.14' 'ceil(x)' 20000000 loops, best of 11: 11.8 nsec per loop λ ./python.exe -m timeit -r 11 -s 'from math import ceil' -s 'x=0.0' 'ceil(x)' 20000000 loops, best of 11: 11.7 nsec per loop λ ./python.exe -m timeit -r 11 -s 'from math import ceil' -s 'x=-3.14E32' 'ceil(x)' 10000000 loops, best of 11: 32.7 nsec per loop λ ./python.exe -m timeit -r 11 -s 'from math import ceil' -s 'x=-323452345.14' 'ceil(x)' 10000000 loops, best of 11: 20.1 nsec per loop ```
1 parent 9c995ab commit 7463f3a

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

Modules/mathmodule.c

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1125,8 +1125,13 @@ static PyObject *
11251125
math_ceil(PyObject *module, PyObject *number)
11261126
/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
11271127
{
1128+
double x;
11281129

1129-
if (!PyFloat_CheckExact(number)) {
1130+
if (PyFloat_CheckExact(number)) {
1131+
x = PyFloat_AS_DOUBLE(number);
1132+
}
1133+
else
1134+
{
11301135
math_module_state *state = get_math_module_state(module);
11311136
PyObject *method = _PyObject_LookupSpecial(number, state->str___ceil__);
11321137
if (method != NULL) {
@@ -1136,11 +1141,10 @@ math_ceil(PyObject *module, PyObject *number)
11361141
}
11371142
if (PyErr_Occurred())
11381143
return NULL;
1144+
x = PyFloat_AsDouble(number);
1145+
if (x == -1.0 && PyErr_Occurred())
1146+
return NULL;
11391147
}
1140-
double x = PyFloat_AsDouble(number);
1141-
if (x == -1.0 && PyErr_Occurred())
1142-
return NULL;
1143-
11441148
return PyLong_FromDouble(ceil(x));
11451149
}
11461150

0 commit comments

Comments
 (0)