0

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.

2
  • crossfoot is faster in both cases. Maybe you missed that it's e-06 when you removed print? In direct comparison, that would be 0.554 vs 2.624 Commented May 28, 2019 at 12:26
  • 1
    @TheGamer007, of course you're right - I must have been blind. Just post it as answer, I'll accept it. Commented May 28, 2019 at 12:35

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.