Skip to content

Commit f5702b6

Browse files
committed
Optimize vector-number math by avoiding RealNumber_Check
PyFloat_AsDouble does basically the same checks internally, so since this is the last case checked in the generic_math functions in math.c, we can just try to convert directly and handle if if the conversion fails.
1 parent eaf3aa0 commit f5702b6

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

src_c/math.c

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -688,7 +688,7 @@ vector_generic_math(PyObject *o1, PyObject *o2, int op)
688688
Py_ssize_t i, dim;
689689
double *vec_coords;
690690
double other_coords[VECTOR_MAX_SIZE] = {0};
691-
double tmp;
691+
double tmp = 0.0;
692692
PyObject *other;
693693
pgVector *vec, *ret = NULL;
694694
if (pgVector_Check(o1)) {
@@ -712,11 +712,15 @@ vector_generic_math(PyObject *o1, PyObject *o2, int op)
712712
if (pg_VectorCoordsFromObj(other, dim, other_coords)) {
713713
op |= OP_ARG_VECTOR;
714714
}
715-
else if (RealNumber_Check(other)) {
716-
op |= OP_ARG_NUMBER;
717-
}
718715
else {
719-
op |= OP_ARG_UNKNOWN;
716+
tmp = PyFloat_AsDouble(other);
717+
if (tmp == -1.0 && PyErr_Occurred()) {
718+
PyErr_Clear();
719+
op |= OP_ARG_UNKNOWN;
720+
}
721+
else {
722+
op |= OP_ARG_NUMBER;
723+
}
720724
}
721725

722726
if (op & OP_INPLACE) {
@@ -761,14 +765,12 @@ vector_generic_math(PyObject *o1, PyObject *o2, int op)
761765
case OP_MUL | OP_ARG_NUMBER:
762766
case OP_MUL | OP_ARG_NUMBER | OP_ARG_REVERSE:
763767
case OP_MUL | OP_ARG_NUMBER | OP_INPLACE:
764-
tmp = PyFloat_AsDouble(other);
765768
for (i = 0; i < dim; i++) {
766769
ret->coords[i] = vec_coords[i] * tmp;
767770
}
768771
break;
769772
case OP_DIV | OP_ARG_NUMBER:
770773
case OP_DIV | OP_ARG_NUMBER | OP_INPLACE:
771-
tmp = PyFloat_AsDouble(other);
772774
if (tmp == 0.) {
773775
PyErr_SetString(PyExc_ZeroDivisionError, "division by zero");
774776
Py_DECREF(ret);
@@ -781,7 +783,6 @@ vector_generic_math(PyObject *o1, PyObject *o2, int op)
781783
break;
782784
case OP_FLOOR_DIV | OP_ARG_NUMBER:
783785
case OP_FLOOR_DIV | OP_ARG_NUMBER | OP_INPLACE:
784-
tmp = PyFloat_AsDouble(other);
785786
if (tmp == 0.) {
786787
PyErr_SetString(PyExc_ZeroDivisionError, "division by zero");
787788
Py_DECREF(ret);
@@ -3971,12 +3972,15 @@ vector_elementwiseproxy_generic_math(PyObject *o1, PyObject *o2, int op)
39713972
return NULL;
39723973
}
39733974
}
3974-
else if (RealNumber_Check(other)) {
3975-
op |= OP_ARG_NUMBER;
3976-
other_value = PyFloat_AsDouble(other);
3977-
}
39783975
else {
3979-
op |= OP_ARG_UNKNOWN;
3976+
other_value = PyFloat_AsDouble(other);
3977+
if (other_value == -1.0 && PyErr_Occurred()) {
3978+
PyErr_Clear();
3979+
op |= OP_ARG_UNKNOWN;
3980+
}
3981+
else {
3982+
op |= OP_ARG_NUMBER;
3983+
}
39803984
}
39813985

39823986
ret = _vector_subtype_new(vec);

0 commit comments

Comments
 (0)