Skip to content

Commit 68e1b65

Browse files
feat: timing_context_manager - A simple timing context manager based on a generator function
1 parent 2211bda commit 68e1b65

File tree

6 files changed

+33
-0
lines changed

6 files changed

+33
-0
lines changed

ebook/chapters/standard_lib_chapters/context_manager.tex

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,21 @@ \subsection{Temporal SQLite Table}
3232
(2, 1)
3333
(5,)
3434
\end{lstlisting}
35+
36+
37+
\subsection{Timing Context Manager}
38+
39+
Sometimes you simply want to find out, how long a certain code block needs to be executed.
40+
To do that you have different options: Use a third-party package like \lstinline{boxx} or create your own timing context manager based on the standard library.
41+
The following Listing shows you, how you can create your own timing context manager.
42+
In specific, this approach makes use of a generator function (you can implement this context manager based on a class as well).
43+
44+
\lstinputlisting[caption=timing\_context\_manager.py]{../standard_lib/timing_context_manager.py}
45+
46+
As you can see, the code is pretty straightforward.
47+
An example output is shown below.
48+
49+
\begin{lstlisting}[caption=Output of timing\_context\_manager.py]
50+
$ python timing_context_manager.py
51+
Time List Comprehension: 0.5184009075164795
52+
\end{lstlisting}

ebook/python-snippets.epub

474 Bytes
Binary file not shown.

ebook/python-snippets.mobi

953 Bytes
Binary file not shown.

ebook/python-snippets.pdf

3.15 KB
Binary file not shown.

standard_lib/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ A collection of useful snippets using only the standard library.
5757
| split_preserving_sub-strings | Python standard lib's `shlex` splitting strings preserving sub-strings |
5858
| string_capitalize | Difference between title() and capitalize() |
5959
| temptable_contextmanager | Create a contextmanager providing a temptable for SQLite |
60+
| timing_context_manager | A simple timing context manager based on a generator function |
6061
| trace_decorator | Trace decorator tracing function calls |
6162
| tree_clone | Python clone of the UNIX tree command - but better! |
6263
| unicode_source_code | Example on how awesome unicode in source code is |
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import time
2+
3+
from contextlib import contextmanager
4+
5+
6+
@contextmanager
7+
def timing(description: str):
8+
start = time.time()
9+
yield
10+
print(f"{description}: {time.time() - start}")
11+
12+
13+
with timing("Time List Comprehension"):
14+
s = [x for x in range(10_000_000)]

0 commit comments

Comments
 (0)