Skip to content

Commit

Permalink
Optimise math.ceil for known exact float
Browse files Browse the repository at this point in the history
This matches a similar optimisation done for math.floor in
python#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
```
  • Loading branch information
hauntsaninja committed Sep 3, 2023
1 parent 9c995ab commit 7463f3a
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions Modules/mathmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -1125,8 +1125,13 @@ 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 +1141,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

0 comments on commit 7463f3a

Please sign in to comment.