Why is python's in-built math operator slow when dealing with large numbers?

Viewed 193
import random , time
print("Please by patient it might take a while to compute the addition of 2 1,000,000 digit long numbers.\n\n")
list1 = [ ]
num1input , num2input = "" , ""
for x in range(1000000) :
    num1input += str(random.randint(0,9))
    num2input += str(random.randint(0,9))
start = time.time()

result = int(num1input) + int(num2input)
end = time.time()-start
#print(result)
print("Time taken for 1,000,000 digits + 1,000,000 digits (python + operator) :\n" + str(end) + " s\n\n")

start = time.time()
for i in range(max([len(num1input) , len(num2input)]) + 1) :
    list1.append(0)
for i2 in range(-1 , -(len(num1input) + 1) , -1) :
    list1[i2] += int(num1input[i2])
for i3 in range(-1 , -(len(num2input) + 1) , -1) :
    list1[i3] += int(num2input[i3])
for i4 in range(-1 , -(len(list1) + 1) , -1) :
    while (list1[i4] >= 10) :
        list1[i4] -= 10
        list1[i4 - 1] += 1
    list1[i4] = str(list1[i4])
result = "".join(list1)
while (result[0] == "0") :
    result = result[1:]
end = time.time()-start
#print(result)
print("Time taken for 1,000,000 digits + 1,000,000 digits (my self built function) :\n" + str(end) + " s")

By using the above code, we can see that the in-built python plus operator took much longer than my custom built function when computing 2 1 million digit long numbers (addition). May I know why the in-built operator performs much better than custom function when dealing with small numbers and much worse when dealing with huge numbers ?

1 Answers

The two methods are not equivalent. The first one spends time converting strings to ints first. If you only measure the addition operation you will see that it is much faster:

n1 = int(num1input)
n2 = int(num2input)

then

start = time.time()
result = n1 + n2
end = time.time()-start

Here is a sample result:

Time taken for 1,000,000 digits + 1,000,000 digits (python + operator) :
0.0009801387786865234 s   

Time taken for 1,000,000 digits + 1,000,000 digits (my self built function) :
7.089484214782715 s
Related