Skip to content

Commit 11a14db

Browse files
authored
gh-157742: Speed up int multiplication by not zeroing the whole result in x_mul() (#157743)
* Speed up int multiplication by not zeroing the whole result first
1 parent 01286cc commit 11a14db

1 file changed

Lines changed: 6 additions & 4 deletions

File tree

‎Objects/longobject.c‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3949,8 +3949,8 @@ x_mul(PyLongObject *a, PyLongObject *b)
39493949
if (z == NULL)
39503950
return NULL;
39513951

3952-
memset(z->long_value.ob_digit, 0, _PyLong_DigitCount(z) * sizeof(digit));
39533952
if (a == b) {
3953+
memset(z->long_value.ob_digit, 0, _PyLong_DigitCount(z) * sizeof(digit));
39543954
/* Efficient squaring per HAC, Algorithm 14.16:
39553955
* https://cacr.uwaterloo.ca/hac/about/chap14.pdf
39563956
* Gives slightly less than a 2x speedup when a == b,
@@ -4021,15 +4021,17 @@ x_mul(PyLongObject *a, PyLongObject *b)
40214021
return NULL;
40224022
});
40234023

4024+
/* Row 0 has nothing to add to yet (z is not zeroed); every
4025+
later row only reads digits that the previous row wrote.
4026+
Compilers split the i == 0 row off into its own loop. */
40244027
while (pb < pbend) {
4025-
carry += *pz + *pb++ * f;
4028+
carry += (i ? *pz : 0) + *pb++ * f;
40264029
*pz++ = (digit)(carry & PyLong_MASK);
40274030
carry >>= PyLong_SHIFT;
40284031
assert(carry <= PyLong_MASK);
40294032
}
4030-
if (carry)
4031-
*pz += (digit)(carry & PyLong_MASK);
40324033
assert((carry >> PyLong_SHIFT) == 0);
4034+
*pz = (digit)carry;
40334035
}
40344036
}
40354037
return long_normalize(z);

0 commit comments

Comments
 (0)