Numbers Are C Numbers Until They Aren't

Contents
In Python, 2**62 * 4 is 18446744073709551616. In a NumPy array of 64-bit integers it is 0, and
NumPy 1.16 doesn’t say a word. Multiply the same value as a single NumPy scalar and you get a
warning and the same 0. Python’s integers have no fixed size, but almost every library that makes
Python fast stores numbers as C integers and C doubles, and at that boundary Python’s arithmetic
quietly becomes C’s. CPython itself sits on both sides: its integers are arbitrary-precision, and its
fastest paths are the ones that can do the work in a C long or double and never build a Python
object at all.
This post measures both sides: what a + b costs as integers grow, where multiplication changes
algorithm, how sum() keeps a running total in a C long until the total gets too big, why
comparing an int with a float is exact in Python when it wouldn’t be in C, and what NumPy’s fixed-width
types do with the same values.
This is Part 9 of a series on the CPython runtime. Part 1 showed that an int is an array of 30-bit digits and a float a C double behind a header. It is written for Python programmers who have written a little C. Everything here ran on CPython 3.7.3, built from its tag with Ubuntu 18.04’s gcc 7.3.0, and NumPy 1.16.4 from PyPI, released on 28 May. The note at the end says exactly where and how.
What a + b does
BINARY_ADD calls PyNumber_Add, which finds the type’s addition slot, and for two ints that is
long_add in Objects/longobject.c:
static PyObject *
long_add(PyLongObject *a, PyLongObject *b)
{
PyLongObject *z;
CHECK_BINOP(a, b);
if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
}
if (Py_SIZE(a) < 0) {
if (Py_SIZE(b) < 0) {
z = x_add(a, b);
...
}
else
z = x_sub(b, a);
}
else {
if (Py_SIZE(b) < 0)
z = x_sub(a, b);
else
z = x_add(a, b);
}
return (PyObject *)z;
}
If both operands have at most one 30-bit digit (|x| < 230), the sum is done with one C
addition: MEDIUM_VALUE reads the digit and applies the sign, and PyLong_FromLong returns a cached
small int or allocates a new object. Otherwise x_add and x_sub run the schoolbook algorithm over
the digit arrays, carrying 30 bits at a time. Either way the result is a new object, so every
arithmetic operation on ints outside −5…256 allocates, and every intermediate value of a Python
expression pays for an allocation and, later, a free.
Cost by size
import sys, timeit
print("%8s %7s %10s %10s" % ("bits", "digits", "a + b ns", "a * b ns"))
for bits in (10, 29, 30, 59, 60, 120, 300, 1000, 2100, 4200, 10000, 30000):
a = (1 << bits) - 12345 if bits > 20 else 1000
b = a - 1
digits = max(1, (a.bit_length() + 29) // 30)
n = 200000 if bits < 2000 else 20000
add = min(timeit.repeat("a + b", globals={"a": a, "b": b}, number=n, repeat=5)) / n * 1e9
mul = min(timeit.repeat("a * b", globals={"a": a, "b": b}, number=n // 10, repeat=5)) / (n // 10) * 1e9
print("%8d %7d %10.1f %10.1f" % (bits, digits, add, mul))
$ python3 addcost.py
bits digits a + b ns a * b ns
10 1 14.7 14.8
29 1 14.8 14.9
30 1 15.4 15.1
59 2 16.2 20.3
60 2 16.0 20.8
120 4 16.3 28.1
300 10 17.8 64.8
1000 34 24.9 478.6
2100 70 40.8 2252.6
4200 140 69.3 6662.4
10000 334 147.5 23182.6
30000 1000 399.8 169059.2
(Each figure includes the cost of the timeit loop and of allocating the result, which is most of the
15 ns at the small end.)
Addition is flat at about 15 ns until the operands are hundreds of bits long. Going from one digit to
two (the bits 29 → 59 rows) costs a nanosecond, and the operation is dominated by the interpreter
and the allocation, not the arithmetic. Past a few hundred digits the digit loop shows: 400 ns for a
thousand digits, linear in size.
Multiplication grows much faster. It is quadratic in the schoolbook range: 10 digits take 65 ns and
34 digits 479 ns. At 70 digits (KARATSUBA_CUTOFF 70 in longobject.c) CPython switches to
Karatsuba’s algorithm, and from there the growth slows. Tripling the size from 334 to 1,000 digits
multiplied the time by 7.3, where schoolbook would multiply it by 9. Python has no faster
multiplication than Karatsuba, so multiplying numbers of millions of digits, which libraries like GMP
do with FFT-based methods, is impractically slow in pure CPython.
The cost of a + b and a * b as integers grow
CPython 3.7.3, nanoseconds per operation against operand size in 30-bit digits. Both axes are logarithmic.
Hover or focus a point for its value.
sum() keeps a C number for as long as it can
Every + on ints makes an object. A loop that adds a million numbers makes a million objects and
frees almost as many. sum() avoids that with a fast path in Python/bltinmodule.c, which keeps the
running total in a C long for as long as both the items and the total fit in one:
/* Fast addition by keeping temporary sums in C instead of new Python objects.
Assumes all inputs are the same type. If the assumption fails, default
to the more general routine.
*/
if (PyLong_CheckExact(result)) {
int overflow;
long i_result = PyLong_AsLongAndOverflow(result, &overflow);
/* If this already overflowed, don't even enter the loop. */
if (overflow == 0) {
Py_DECREF(result);
result = NULL;
}
while(result == NULL) {
item = PyIter_Next(iter);
...
if (PyLong_CheckExact(item)) {
long b = PyLong_AsLongAndOverflow(item, &overflow);
long x = i_result + b;
if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
i_result = x;
Py_DECREF(item);
continue;
}
}
/* Either overflowed or is not an int. Restore real objects and process normally */
The (x^i_result) >= 0 || (x^b) >= 0 test is the classic two’s-complement check for “this signed
addition didn’t overflow”: if the sum has a different sign from both operands, it wrapped. It needs
the addition to wrap in the first place, which C leaves undefined for signed integers, and CPython makes
it well defined by compiling everything with -fwrapv (it was in the compiler flags Part 1 printed). Floats get an equivalent
path that accumulates in a C double. How much the C total saves, and what turns it off:
import timeit
xs = list(range(1000000))
fs = [float(x) for x in xs]
def loop(xs):
t = 0
for x in xs:
t += x
return t
for label, stmt in [("sum(ints)", "sum(xs)"),
("sum(ints, start=2**63)", "sum(xs, 2**63)"),
("sum(floats)", "sum(fs)"),
("loop over ints", "loop(xs)")]:
best = min(timeit.repeat(stmt, globals=globals(), number=1, repeat=7))
print("%-24s %6.2f ms" % (label, best * 1e3))
$ python3 sumfast.py
sum(ints) 3.61 ms
sum(ints, start=2**63) 8.51 ms
sum(floats) 2.52 ms
loop over ints 14.06 ms
The same million ints take 3.6 ms with sum() and 14 ms in a Python loop, and nearly all the
difference is objects that sum() never makes. Starting the total at 263, one past the
largest C long, makes the very first PyLong_AsLongAndOverflow overflow, so the fast path is never
entered, and the same sum takes 8.5 ms, the cost of a Python int object per partial sum. A total that
starts small and grows past 263 halfway through switches paths halfway through. The
answer is the same in every case. The speed depends on whether the numbers happen to fit a C type,
which nothing in the code says.
Floats are C doubles, comparisons are not C’s
A float is a C double, and every surprise of binary floating point applies (Part 1 read 0.1’s
bytes). But Python doesn’t compare ints and floats the way C does. In C, n == f with an integer n
and a double f converts n to a double first, and two numbers that differ can compare equal.
Python compares the exact values:
n = 2**53 + 1
f = float(n)
print("n =", n)
print("float(n) =", repr(f), " int(float(n)) =", int(f))
print("n == f :", n == f)
print("n > f :", n > f)
print("n == n + 0.0:", n == n + 0.0)
print("hash(n) == hash(f):", hash(n) == hash(f), " hash(2**53) == hash(2.0**53):", hash(2**53) == hash(2.0**53))
$ python3 compare.py
n = 9007199254740993
float(n) = 9007199254740992.0 int(float(n)) = 9007199254740992
n == f : False
n > f : True
n == n + 0.0: False
hash(n) == hash(f): False hash(2**53) == hash(2.0**53): True
253 + 1 is the first integer a double can’t represent. Converting it rounds to
253, so in C the comparison would be true. Python says n == f is false and n > f true,
because they are different numbers, and even n == n + 0.0 is false, since the addition happened in
floating point. The work is in float_richcompare in Objects/floatobject.c, which converts the int
to a double only when that’s exact:
if (nbits <= 48) {
j = PyLong_AsDouble(w);
/* It's impossible that <= 48 bits overflowed. */
assert(j != -1.0 || ! PyErr_Occurred());
goto Compare;
}
An int of 48 bits or fewer converts exactly, so it compares as doubles. A bigger one is compared by
exponent first and then, if needed, by converting the float to an exact int. The hashes follow the
same rule: equal numbers of any type must hash alike, so hash(2**53) == hash(2.0**53), while n and
f hash differently because they aren’t equal. The consequence is that a dict keyed by large ints
won’t find the entry for n when you look up float(n). It’s Python’s numeric tower working as
specified, and it’s a difference from every C-based numerical library that compares by conversion.
One integer, three representations · calculator
Type an integer, or pick one. Python keeps it exactly; C's fixed types don't.
Python's int: ob_size holds the sign and the number of 30-bit digits, least significant first. C's int64_t keeps the value modulo 264, as a NumPy int64 array does. A double keeps 53 significant bits.
NumPy: C numbers with Python syntax
NumPy stores arrays as C arrays, and its integers are C integers of a fixed width. Arithmetic on them is C arithmetic, done in compiled loops, without a Python object per element, which is why it’s fast and why it isn’t Python’s:
import sys, warnings
import numpy as np
print("numpy", np.__version__, " default int:", np.array([1]).dtype, " C long:", np.dtype("long"))
a = np.array([2**62, 2**62], dtype=np.int64)
print("array: 2**62 * 4 ->", a * 4, " (Python int:", 2**62 * 4, ")")
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
s = np.int64(2**62) * 4
print("scalar: 2**62 * 4 ->", s, " warnings:", [str(x.message) for x in w])
print("np.array([2**63 - 1]).dtype:", np.array([2**63 - 1]).dtype)
print("np.array([2**63]).dtype: ", np.array([2**63]).dtype)
print("np.array([2**64]).dtype: ", np.array([2**64]).dtype)
u = np.full(1000, 200, dtype=np.uint8)
print("1000 x uint8 200: u.sum() =", u.sum(), " u.sum(dtype=np.uint8) =", u.sum(dtype=np.uint8), " (u + u)[0] =", (u + u)[0])
print("type(a[0]):", type(a[0]).__name__, " sys.getsizeof(a[0]):", sys.getsizeof(a[0]), " a.itemsize:", a.itemsize)
$ python3 numpyints.py
numpy 1.16.4 default int: int64 C long: int64
array: 2**62 * 4 -> [0 0] (Python int: 18446744073709551616 )
scalar: 2**62 * 4 -> 0 warnings: ['overflow encountered in long_scalars']
np.array([2**63 - 1]).dtype: int64
np.array([2**63]).dtype: uint64
np.array([2**64]).dtype: object
1000 x uint8 200: u.sum() = 200000 u.sum(dtype=np.uint8) = 64 (u + u)[0] = 144
type(a[0]): int64 sys.getsizeof(a[0]): 32 a.itemsize: 8
- Arrays wrap silently. 262 × 4 = 264, which is 0 modulo 264. The
array multiply is a C loop over
int64_t, and it checks nothing. - Scalars warn. The same multiply on a single
np.int64goes through NumPy’s scalar code, which checks for overflow and issues aRuntimeWarning, and still returns 0. - The dtype depends on the value.
2**63 - 1fitsint64.2**63doesn’t, so NumPy picksuint64.2**64fits no C integer type, so the array becomesobject: an array of pointers to Python ints, with Python’s arithmetic and none of NumPy’s speed. The same line of code produces three kinds of array depending on the data. - Accumulation is promoted, element-wise arithmetic is not.
u.sum()of a thousanduint8200s is 200,000, because NumPy accumulates small integer types in the platform integer. Asking for auint8result gives 200,000 mod 256 = 64, andu + ugives 400 mod 256 = 144 in every element. - An element taken out of an array is a 32-byte Python object (
numpy.int64, a header and the value) for an 8-byte item, created on access.
The default integer type is the C long. On 64-bit Linux and macOS that’s 64 bits. On 64-bit Windows a
C long is 32 bits (the LLP64 data model), so NumPy’s default integer there is int32, and the same
program overflows at 231 on Windows and 263 on Linux. The number in your
Python code is the same. The C type under it is the platform’s.
What we covered
long_addadds ints below 230 with one C addition. Larger ones go through a digit-by-digit loop, and every result outside the small-int cache is a new object.- Addition stayed at about 15 ns up to a few hundred bits and was 400 ns at a thousand digits. Multiplication is schoolbook (quadratic) below 70 digits and Karatsuba above, 169 µs at a thousand digits.
sum()keeps its total in a Clong(ordouble) while everything fits: 3.6 ms for a million ints, 8.5 ms when the start value made it give up, 14 ms as a Python loop.- Comparisons between ints and floats are exact: 253 + 1 is not equal to its own float conversion, unlike in C, and dict lookups follow the same rule.
- NumPy’s integers are C integers. Arrays wrap without a warning, scalars warn, the dtype depends on the
values, small types are promoted when summed but not when added, and the default width follows the
platform’s C
long.
The next post crosses the same boundary from the other direction: writing a C extension by hand, the reference-counting rules it must follow, and what calling into C costs from Python.
A note on the evidence
What I ran, and where. Everything ran on CPython 3.7.3, built from the v3.7.3 tag with Ubuntu
18.04’s gcc 7.3.0, with NumPy 1.16.4 installed from PyPI with that interpreter’s pip, on a minimal 18.04
userland from the release archive, as a chroot on a 64-bit x86 machine. Each script was extracted from
this page and run as shown.
The numbers. The timings are the best of 5 (addcost.py) or 7 (sumfast.py) repeats on an idle
machine, and they include timeit’s own loop and the allocation of each result. Their absolute values
belong to this machine. The shape (flat addition, quadratic then sub-quadratic multiplication, sum()
two to four times faster than the alternatives) is the point. A second run of every script on this page,
extracted from the page, gave every timing within 3% of the ones shown. The NumPy and comparison
outputs are deterministic.
What I worked out rather than read. That the start value of 263 turns off the whole
fast path (rather than only part of it) is from reading builtin_sum_impl. The Karatsuba growth rate
is inferred from three timings, which isn’t enough to measure an exponent. It only shows the change
from the schoolbook rate.
What I cited rather than ran. The C quoted here is from the v3.7.3 tag: Objects/longobject.c
(long_add, MEDIUM_VALUE, KARATSUBA_CUTOFF), Python/bltinmodule.c (builtin_sum_impl) and
Objects/floatobject.c (float_richcompare). Karatsuba’s algorithm is from Karatsuba and Ofman’s 1962
paper, describing his 1960 result. The Windows int32 default is from NumPy’s documentation and the
LLP64 model. I didn’t run it on Windows.
What I’d still change. I timed a + b and a * b with the operands bound in globals, so each
measurement includes two LOAD_GLOBALs. Subtracting an empty-loop baseline, as Part 2 did, would isolate
the arithmetic. And a comparison with GMP through gmpy2 would show how far CPython’s integers are from
the state of the art at large sizes.
Numbers Are C Numbers Until They Aren't