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 ?