Timing python functions
I have been writing some performant code in Python (oxymoron?), and I wanted a simple decorator to time funtions essentially to measure running time.
There a plenty of modules in Python that can help with this, but most were complicated for me to understand what exactly they were doing and had way more functionaltiy than I required.
So I wrote a tiny package that can help with this. The package is named tiemy
and is available in pypi, it only has one single decorator, timer
and I would like to keep it to a minimum.
You just have to use the decorator @timer
on any Python callable and tiemy runs the function for 3 times and displays the mean and standard deviation of the run time.
At the core tiemy uses perf_counter
from time module to measure running time.
Installing tiemy
The module is fairly easy to install, you just need python and pip:
pip install tiemy
That’s it!
How to use tiemy
Consider a prime number sieve as below is saved in a file prime.py
from tiemy import timer
@timer
def sundaram(N):
"""sundaram's sieve to find non primes."""
= list(range(3, N, 2))
primes = N // 2
half = 4
init for step in range(3, N, 2):
for i in range(init, half, step):
-1] = 0
primes[i+= 2 * (step + 1)
init if init > half:
return [2] + list(filter(0, numbers))
if __name__ == "__main__":
100000) sundaram(
The output would be something like:
python prime.py
timing func:: sundaram0.0090, std: 0.0003 sec. mean:
The above method to find prime numbers is called sundaram sieve 1, we will look at it more in detail in a later post :).
The end
Tiemy, pronunced astie-mee
, is a simple timing decorator that just does one thing, measure running time.