+10 votes
1 view
in Python by (80.9k points)

How should I use the timeit module if I want to start counting time somewhere in my code and then get the passed time? I think I am using the module wrong.

import timeit
start = timeit.timeit()
print "hello"
end = timeit.timeit()
print end - start

2 Answers

+10 votes
by (37.4k points)

To measure the elapsed wall-clock time between 2 points, you may use time.time():

The following code gives the execution time in seconds:

import time

start = time.time()


end = time.time()

print(end - start)

0 votes
by (107k points)
edited by

I will suggest you use timeit.default_timer instead of timeit.timeit. timeit.default_timer provides the best clock available on your platform and version of Python automatically:-

from timeit import default_timer as timer

start = timer() 

end = timer() 

print(end - start)

# It will print Time in seconds, e.g. 5.38091952400282


The timeit.default_timer is assigned to time.time() or time.clock() depending on OS. On Python 3.3+ default_timer is time.perf_counter() on all platforms

To know more about this you can have a look at the following video:-

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !