Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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())
Copy link
Contributor

@skirpichev skirpichev Sep 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will be partially covered by tests.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After merging #102523 this should be fixed.

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