iatechicken
iatechicken

Reputation: 171

Why do run times differ among digit-by-digit algorithm for the same solution

Just out of curiosity, I ran a simple digit by digit algorithm to find the square root of the same value 20 times (sigh I know...)

I got the same results for all 20 runs, but the run time differed across all executions. Is this an expected observation or did I code the timer poorly?

def tester(orange):   
    import timeit
    x = orange
    step = 1
    guess = 0
    epsilon = 0.0000000001
    start = timeit.default_timer()


    while guess ** 2 < x:
        guess += step
        if guess ** 2 > x:
            guess -= step
            if step > epsilon:
                step = step / 10
            else:
                break

    print("The square root of", x, "is", guess)

    stop = timeit.default_timer()

    print('Time: ', stop - start) 

number = int(input("Enter the number of times that you want to run this test: "))
answer = float(input("Enter a number to find the square root for: "))
while number > 0:
    tester(answer)
    number -= 1

Upvotes: 1

Views: 44

Answers (1)

Vineeth Sai
Vineeth Sai

Reputation: 3455

timeit.default_timer() measures the wall clock time not CPU time. For that reason, Other processes(Background processes included) running on your computer will impact its time. You can see this in action if you run your code for some 100 times and open chrome and mess with it while it's running. You'll see a small increase in time because chrome is using a fraction of your cpu's time.

To get a more accurate estimate of your code use timeit.timeit.

More here

Upvotes: 0

Related Questions