Skip to content

Latest version Python 3.10 | 3.11 | 3.12+ MIT license Codecov CodeQL Test Downloads

Timer for Python ⏳#

Introduction#

Performance timing made easy. When you want to measure how much time it takes to run Python programs and gauge performance of multiple blocks of code, Timer for Python is a lightweight Python package that gets the job done.

How It Works#

Basics#

Simply wrap the Timer around a block of code that you want to measure:

Python
1
2
3
4
5
6
7
8
from timer import Timer

timer = Timer()
timer.start()

# Insert your code here

timer.stop()

After timer.stop(), the elapsed time will be printed in your terminal. Example:

Elapsed time: 12.34 seconds

Context Manager#

Alternatively, use the with statement. This will automatically start and stop the Timer – and so no need to declare timer.start() and timer.stop(). Same result as before, but less code:

Python
1
2
3
4
from timer import Timer

with Timer():
    # Insert your code here

Terminal output example:

Elapsed time: 12.34 seconds

Function Decorator#

Or use @benchmark_timer as function decorator:

Python
1
2
3
4
5
6
7
from timer import benchmark_timer

@benchmark_timer
def test_function():
    # Insert your code here

test_function()

Terminal output example:

Elapsed time: 12.34 seconds for thread TEST_FUNCTION

Ready to try? Let's get started.