Trufa
Trufa

Reputation: 40717

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.

Upvotes: 0

Views: 665

Answers (2)

user35147863
user35147863

Reputation: 2595

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().

Upvotes: 2

dting
dting

Reputation: 39287

I haven't compared this way to timeit but sometimes i use datetime subtractions for quick and dirty timing. I'll run some tests when i get home and compare.

import datetime

x = 1
count = 0
userInput = 1
epsilon = 1

start = datetime.datetime.now()

while (abs(x**2 - userInput) > epsilon):
    x = 0.5 * (x + (userInput/x))
    count = count+1

print datetime.datetime.now() - start, "s"

results in:

0:00:00.000011 s

Upvotes: 0

Related Questions