Skip to content

Commit

Permalink
pythongh-110489: Optimise math.ceil for known exact float (python#108801
Browse files Browse the repository at this point in the history
)

This matches a similar optimisation done for math.floor in
python#21072
  • Loading branch information
hauntsaninja committed Oct 6, 2023
1 parent 201dc11 commit f013b47
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Optimise :func:`math.ceil` when the input is exactly a float, resulting in about a 10% improvement.
16 changes: 9 additions & 7 deletions Modules/mathmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -1125,8 +1125,12 @@ static PyObject *
math_ceil(PyObject *module, PyObject *number)
/*[clinic end generated code: output=6c3b8a78bc201c67 input=2725352806399cab]*/
{
double x;

if (!PyFloat_CheckExact(number)) {
if (PyFloat_CheckExact(number)) {
x = PyFloat_AS_DOUBLE(number);
}
else {
math_module_state *state = get_math_module_state(module);
PyObject *method = _PyObject_LookupSpecial(number, state->str___ceil__);
if (method != NULL) {
Expand All @@ -1136,11 +1140,10 @@ math_ceil(PyObject *module, PyObject *number)
}
if (PyErr_Occurred())
return NULL;
x = PyFloat_AsDouble(number);
if (x == -1.0 && PyErr_Occurred())
return NULL;
}
double x = PyFloat_AsDouble(number);
if (x == -1.0 && PyErr_Occurred())
return NULL;

return PyLong_FromDouble(ceil(x));
}

Expand Down Expand Up @@ -1196,8 +1199,7 @@ math_floor(PyObject *module, PyObject *number)
if (PyFloat_CheckExact(number)) {
x = PyFloat_AS_DOUBLE(number);
}
else
{
else {
math_module_state *state = get_math_module_state(module);
PyObject *method = _PyObject_LookupSpecial(number, state->str___floor__);
if (method != NULL) {
Expand Down

0 comments on commit f013b47

Please sign in to comment.