To get the elapsed time in seconds, you can use timeit.default_timer():
import timeit
start_time = timeit.default_timer()
# code you want to evaluate
elapsed = timeit.default_timer() - start_time
timeit.default_timer() is used instead of time.time() or time.clock() because it will choose the timing function that has the higher resolution for any platform.
To get the elapsed time in seconds, you can use timeit.default_timer():
import timeit
start_time = timeit.default_timer()
# code you want to evaluate
elapsed = timeit.default_timer() - start_time
timeit.default_timer() is used instead of time.time() or time.clock() because it will choose the timing function that has the higher resolution for any platform.
I always use a decorator to do some extra work for a existing function, including to get the execution time. It is pythonic and simple.
import time
def time_usage(func):
def wrapper(*args, **kwargs):
beg_ts = time.time()
retval = func(*args, **kwargs)
end_ts = time.time()
print("elapsed time: %f" % (end_ts - beg_ts))
return retval
return wrapper
@time_usage
def test():
for i in xrange(0, 10000):
pass
if __name__ == "__main__":
test()
You can use time.time() or time.clock() before and after the block you want to time.
import time
t0 = time.time()
code_block
t1 = time.time()
total = t1-t0
This method is not as exact as timeit (it does not average several runs) but it is straightforward.
time.time() (in Windows and Linux) and time.clock() (in Linux) are not precise enough for fast functions because they return the time in an integer number of seconds (you'll get total = 0 for short durations). In this case or if you want to average the time elapsed by several runs, you have to manually call the function multiple times (As I think you already do in you example code and timeit does this automatically when you set its number argument)
import time
def myfast():
code
n = 10000
t0 = time.time()
for i in range(n): myfast()
t1 = time.time()
total_n = t1-t0
In Windows, time.clock() has higher precision because it returns the time in microseconds whereas time.time() returns the time in seconds. So choose whichever makes sense for your situation.
If you are profiling your code and can use IPython, it has the magic function %timeit.
%%timeit operates on cells.
In [2]: %timeit cos(3.14)
10000000 loops, best of 3: 160 ns per loop
In [3]: %%timeit
...: cos(3.14)
...: x = 2 + 3
...:
10000000 loops, best of 3: 196 ns per loop
This would be a good use of a decorator. You could write a decorator that does that like this
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
print('The function ran for', time.time() - start)
return wrapper
@timer
def just_sleep():
time.sleep(5)
just_sleep()
Output
The function ran for 5.0050904750823975
and then you can decorate any function you want to time with @timer and you can also do some other fancy things inside the decorator. Like if the function ran for more than 15 seconds do something...else do another thing
Note: This is not the most accurate way to measure execution time of a function in python
You can build your own context manager to time relatively long bits of code.
import time
class MyTimer(object):
def __enter__(self):
self.start = time.clock()
return self
def __exit__(self, typ, value, traceback):
self.duration = time.clock() - self.start
with MyTimer() as timer:
time.sleep(3)
print(timer.duration)
But be careful about what you are measuring. On Linux time.clock is cpu run time, but on Windows (where cpu run time is not easily available) it is a wall-clock.
You can do this with the with statement. For example:
import time
from contextlib import contextmanager
@contextmanager
def measureTime(title):
t1 = time.clock()
yield
t2 = time.clock()
print '%s: %0.2f seconds elapsed' % (title, t2-t1)
To be used like this:
def myFunc():
#...
with measureTime('myFunc'):
#block of code to time here
#...
You can set up a variable to refer to the code block you want to time by putting that block inside Python's triple quotes. Then use that variable when instantiating your timeit object. Somewhat following an example from the Python timeit docs, I came up with the following:
import timeit
code_block = """\
total = 0
for cnt in range(0, 1000):
total += cnt
print total
"""
tmr = timeit.Timer(stmt=code_block)
print tmr.timeit(number=1)
Which for me printed:
499500
0.000341892242432
(Where 499500 is the output of the timed block, and 0.000341892242432 is the time running.)