Here are my findings after going through many good answers here as well as a few other articles.
First, if you are debating between timeit
and time.time
, the timeit
has two advantages:
timeit
selects the best timer available on your OS and Python version.
timeit
disables garbage collection, however, this is not something you may or may not want.
Now the problem is that timeit
is not that simple to use because it needs setup and things get ugly when you have a bunch of imports. Ideally, you just want a decorator or use with
block and measure time. Unfortunately, there is nothing built-in available for this so you have two options:
Option 1: Use timebudget library
The timebudget is a versatile and very simple library that you can use just in one line of code after pip install.
@timebudget # Record how long this function takes
def my_method():
# my code
Option 2: Use my small module
I created below little timing utility module called timing.py. Just drop this file in your project and start using it. The only external dependency is runstats which is again small.
Now you can time any function just by putting a decorator in front of it:
import timing
@timing.MeasureTime
def MyBigFunc():
#do something time consuming
for i in range(10000):
print(i)
timing.print_all_timings()
If you want to time portion of code then just put it inside with
block:
import timing
#somewhere in my code
with timing.MeasureBlockTime("MyBlock"):
#do something time consuming
for i in range(10000):
print(i)
# rest of my code
timing.print_all_timings()
Advantages:
There are several half-backed versions floating around so I want to point out few highlights:
- Use timer from timeit instead of time.time for reasons described earlier.
- You can disable GC during timing if you want.
- Decorator accepts functions with named or unnamed params.
- Ability to disable printing in block timing (use
with timing.MeasureBlockTime() as t
and then t.elapsed
).
- Ability to keep gc enabled for block timing.