You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
sum() relies on C signed overflow behaviour #80972
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
assignee=Noneclosed_at=<Date2019-05-12.09:39:22.573>created_at=<Date2019-05-04.05:54:49.017>labels= ['interpreter-core', '3.8', 'type-bug', '3.7']
title='sum() relies on C signed overflow behaviour'updated_at=<Date2019-05-12.09:39:22.573>user='https://github.com/serhiy-storchaka'
sum() assumes that an arithmetic operation on signed longs will wrap modulo 2**(bits_in_long) on overflow. However, signed overflow causes undefined behaviour according to the C standards (e.g., C99 6.5, para. 5), and gcc is known to assume that signed overflow never occurs in correct code, and to make use of this assumption when optimizing.
I tested few cases (all positive, all negative, mixed), and did not found any performance difference after this change.
./python -m perf timeit -s "a = list(range(10**4))" -- "sum(a)"
./python -m perf timeit -s "a = [-i for i in range(10**4)]" -- "sum(a)"
./python -m perf timeit -s "a = [i*(-1)**i for i in range(10**4)]" -- "sum(a)"
Activity
serhiy-storchaka commentedon May 4, 2019
sum() assumes that an arithmetic operation on signed longs will wrap modulo 2**(bits_in_long) on overflow. However, signed overflow causes undefined behaviour according to the C standards (e.g., C99 6.5, para. 5), and gcc is known to assume that signed overflow never occurs in correct code, and to make use of this assumption when optimizing.
See also bpo-7406.
serhiy-storchaka commentedon May 4, 2019
I tested few cases (all positive, all negative, mixed), and did not found any performance difference after this change.
./python -m perf timeit -s "a = list(range(10**4))" -- "sum(a)"
./python -m perf timeit -s "a = [-i for i in range(10**4)]" -- "sum(a)"
./python -m perf timeit -s "a = [i*(-1)**i for i in range(10**4)]" -- "sum(a)"
serhiy-storchaka commentedon May 5, 2019
New changeset 2950073 by Serhiy Storchaka in branch 'master':
bpo-36791: Safer detection of integer overflow in sum(). (GH-13080)
2950073
mdickinson commentedon May 12, 2019
Can this be closed, or does the fix need to be backported?
miss-islington commentedon May 12, 2019
New changeset b7e483b by Miss Islington (bot) in branch '3.7':
bpo-36791: Safer detection of integer overflow in sum(). (GH-13080)
b7e483b