Reputation: 1538
I've written two different crossfoot functions, one uses simple integer calculation and one string conversion.
After measuring time, the results have been as expected. String conversion is somewhat slower.
But! If one does not print the result, but only makes an assignment to a variable, the timing is the opposite. Why?
Here's the code:
import time
def crossfoot(num, iterated=False):
result = 0
while num:
result += num % 10
num //= 10
if iterated:
num = result
result = 0
while num:
result += num % 10
num //= 10
return result
def crossfoot2(num, iterated=False):
digits = [int(x) for x in str(num)]
result = sum(digits)
if iterated and result > 9:
return crossfoot2(result, True)
return result
And here's the testing I've made:
start = time.process_time()
res = crossfoot(20991231235959, True)
print(res)
end = time.process_time()
print("Crossfoot : {}".format(end-start))
start = time.process_time()
res = crossfoot2(20991231235959, True)
print(res)
end = time.process_time()
print("Crossfoot2: {}".format(end-start))
Results with given code:
Crossfoot : 2.0396000000002384e-05
Crossfoot2: 3.288599999999933e-05
If one removes the lines with print(res)
the first function will be way slower than the second one.
Results with print removed:
Crossfoot : 5.549999999999999e-06
Crossfoot2: 2.6244000000001655e-05
What is the reason for that?
This is not time critical, but I'd like to understand the cause.
Upvotes: 0
Views: 33
Reputation: 3000
crossfoot
remains faster in both cases. You probably missed that it's e-06
when you remove the print
call.
With both at e-05
, that would be 0.554 vs 2.624
Upvotes: 1