Search code examples
pythontimerprecisionmilliseconds

Get a more precise timer in python


Given this example code:

start = time.clock()

while (abs(x**2 - userInput) > epsilon):

    x = 0.5 * (x + (userInput/x))
    count = count+1

end = time.clock()

print(end-start)

And given that this operation, take very little time, how can I get a more precise timer?

I have looked at timeit module but could not figure out how to use it or whether it is what I want.


Solution

  • Using timeit is simple. A Timer instance takes two strings, the first containing the operations to time, and the second containing setup operations that are performed once before timing begins. The following code should work, just change the variable values to whatever you want.

    import math
    import time
    from timeit import Timer
    
    userInput = "0"
    
    while not userInput.isdigit() or int(userInput) <= 0:
    
        userInput = input("Calcular la raiz de: ") #Get input from user (userInput)
    
    userInput = int(userInput)
    
    epsilon = 0.000001
    x=1
    count=0
    
    setup = 'from __main__ import userInput, epsilon, x, count'
    
    operations = '''
    x = 1
    count = 0
    while (abs(x**2 - userInput) > epsilon):
    
        x = 0.5 * (x + (userInput/x))
        count = count+1
    '''
    
    print('The operations took %.4f microseconds.' % Timer(operations, setup).timeit(1))
    
    #run the operations again to get the x and count values
    x = 1
    count = 0
    while (abs(x**2 - userInput) > epsilon):
    
        x = 0.5 * (x + (userInput/x))
        count = count+1
    print("La raíz de", userInput, "es:",x,"implicó",count,"intentos")
    

    This will run your code a default of one million times and return the total time in seconds it took to run. You can run it a different number of times by passing a number into timeit().