Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mherrmann/timer-cm
A Python context manager for measuring execution time
https://github.com/mherrmann/timer-cm
python
Last synced: 17 days ago
JSON representation
A Python context manager for measuring execution time
- Host: GitHub
- URL: https://github.com/mherrmann/timer-cm
- Owner: mherrmann
- License: mit
- Created: 2017-04-21T12:51:28.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2018-07-19T09:30:38.000Z (over 6 years ago)
- Last Synced: 2024-10-12T18:28:55.908Z (about 1 month ago)
- Topics: python
- Language: Python
- Size: 3.91 KB
- Stars: 48
- Watchers: 3
- Forks: 7
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# timer-cm
A Python context manager for measuring execution time. Useful in conjunction with [Python's profilers](https://docs.python.org/3.5/library/profile.html), or on its own.## Installation
```
pip install timer_cm
```## Usage
First, import the `Timer` class:```python
from timer_cm import Timer
```Then use it as a context manager. In this example we use Python's `sleep(...)` function to pause execution for one second:
```python
with Timer('Simple task'):
sleep(1)
```This produces the following output:
```
Simple task: 1.005s
```Often you want to know where a long running code block spends its time. Use `timer.child(name)` to track individual steps:
```python
with Timer('Long task') as timer:
with timer.child('large step'):
sleep(1)
for _ in range(5):
with timer.child('small step'):
sleep(.5)
```Output:
```
Long task: 3.506s
5x small step: 2.503s (71%)
1x large step: 1.001s (28%)
```To measure times throughout the entire run of your application and report total running times at the end:
```python
from timer_cm import Timer_TIMER = Timer('my_fn')
def my_fn():
# Suppose this function is called throughout your application.
with _TIMER.child('step 1'):
...
with _TIMER.child('step 2'):
...
...import atexit
atexit.register(_TIMER.print_results)```