Skip to content

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

Timer for Python ⏳#

Why Use a Timer?#

Measuring time and performance should be easy. If you want to measure the time it takes to run Python programs and measure the performance of multiple blocks of code, Timer for Python is a lightweight package that does the job.

How It Works#

Basic Usage#

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 the terminal:

% Elapsed time: 12.34 seconds

Context Manager#

Alternatively, use the with statement. This will automatically start and stop the clock – 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

How it appears in the terminal:

% Elapsed time: 12.34 seconds

Multiple Threads#

Gain total flexibility to measure the performance of different blocks of code using multiple threads:

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

with Timer(thread="A")
    # Insert your code here

    with Timer(thread="B", decimals=5):
        # Insert more code here

    # Insert even more code here

How it appears in the terminal:

% Elapsed time: 0.12345 seconds for thread B
% Elapsed time: 6.78 seconds for thread A

Function Decorator#

Or use @function_timer() as function decorator to measure the performance of a function:

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

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

test_function()

How it appears in the terminal:

% Elapsed time: 12.34 seconds for thread TEST_FUNCTION

Next Steps#

Ready to try? Let's get started.

Become a Sponsor

If you find this project helpful, please consider supporting its development. Your donations will help keep it alive and growing. Every contribution, no matter the size, makes a difference.

Donate on GitHub Sponsors

Thank you for your support! 🙌