Search code examples
pythonperformance

Why is python calculation with float numbers faster than calculation with integer numbers


This example shows that python calcuation with float numbers is faster than with integer numbers. I am wondering why calculation with integer is not faster than with float

import time
# Number of operations
N = 10**7

# Integer addition
start_time = time.time()
int_result = 0
for i in range(N):
    int_result += 1
int_time = time.time() - start_time

# Float addition
start_time = time.time()
float_result = 0.0
for i in range(N):
    float_result += 1.0
float_time = time.time() - start_time

print(f"Time taken for integer addition: {int_time:.6f} seconds")
print(f"Time taken for float addition: {float_time:.6f} seconds")

Solution

  • Python uses integers with no fixed size. Under the hood it's an array of digits (not base-10 digits, but fixed size integers that fit into 1 array element, to which we refer as "digit" in this case) that can be extended if needed. That's why you can have absurdly large integers in Python.

    CPUs have instructions to perform floating point operations and integer operations, but they usually only work with numbers that are 1 machine word long or less. Python integers do not satisfy this condition, but floats do.

    Without diving too much into long number arithmetic, integers operations in Python are computed digit by digit. The longer the integers are, the longer the computation takes.

    In your code however, the ints do not use more than 1 digit. Still, these are arrays, that require some overhead to be processed.