garg10may
garg10may

Reputation: 6180

Timeit timing a python function

I am trying to time the below function, however it shows me the error, can't import name val_in_range, what's the error, is there any other method to do it better?

import timeit

x = 10000000

def val_in_range(x, val):
    return val in range(x)

print (val_in_range(x,x/2))

timeit.timeit( 'val_in_range(x,x/2)', 'from __main__ import val_in_range, x',  number=10)

Output:

True
Traceback (most recent call last):
  File "python", line 11, in <module>
  File "<timeit-src>", line 3, in inner
ImportError: cannot import name 'val_in_range'

Upvotes: 2

Views: 1859

Answers (1)

maharshi
maharshi

Reputation: 594

replace timeit.timeit( 'val_in_range(x,x/2)', 'from __main__ import val_in_range, x', number=10)

with timeit.timeit(lambda:val_in_range(x,x/2), number=10)

you can print the value directly using the print statement.

Upvotes: 3

Related Questions