We here define a decorator that at the beginning of the execution remembers the time, and at the end of the exexution prints the time elapse. Note that this is wallclock time, not process time, so it will depend on what else is going on at that moment source
In [1]:
import time
def time_usage(func):
def wrapper(*args, **kwargs):
beg_ts = time.time ()
func(*args, **kwargs)
end_ts = time.time ()
print("elapsed time: %f" % (end_ts - beg_ts))
return wrapper
To always time execution of a function, just add the decorator to its definition...
In [2]:
@time_usage
def test():
for i in range(0, 100000):
pass
...and whenever the function is run it will print the time spent in it
In [3]:
test()
In [4]:
import time
def new_timer(id=''):
beg_ts = time.time ()
def finish():
end_ts = time.time ()
print("%s elapsed time: %f" % (id, end_ts - beg_ts))
return end_ts - beg_ts
return finish
The way it works is as follows
In [5]:
mytimer = new_timer('TIMERID')
for i in range(0, 100000):
pass
mytimer()
Out[5]:
timeit
For timing the execution time of snippets - eg to compare different ways of programming the same thing - there is a function called timeit
in the eponymous module source
In [6]:
import timeit
timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
Out[6]:
In [7]:
timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
Out[7]:
In [8]:
timeit.timeit('"-".join(map(str, range(100)))', number=10000)
Out[8]:
(c) Stefan Loesch / oditorium 2014; all rights reserved (license)
In [9]:
import sys
print(sys.version)