Debian Codegraph @

README.md

raw
1 [![Python Timer Functions: Three Ways to Monitor Your Code](https://files.realpython.com/media/Three-Ways-to-Time-Your-Code_Watermarked.8d561fcc7a35.jpg)](https://realpython.com/python-timer)
2
3 # `codetiming` - A flexible, customizable timer for your Python code
4
5 [![Latest version](https://img.shields.io/pypi/v/codetiming)](https://pypi.org/project/codetiming/)
6 [![Python versions](https://img.shields.io/pypi/pyversions/codetiming)](https://pypi.org/project/codetiming/)
7 [![Downloads](https://img.shields.io/pypi/dd/codetiming)](https://pypi.org/project/codetiming/)
8 [![Tests](https://img.shields.io/github/workflow/status/realpython/codetiming/unit_tests?label=tests)](https://github.com/realpython/codetiming/actions)
9 [![Checked with mypy](http://www.mypy-lang.org/static/mypy_badge.svg)](http://mypy-lang.org/)
10 [![Interrogate DocStrings](https://raw.githubusercontent.com/realpython/codetiming/main/interrogate_badge.svg)](https://interrogate.readthedocs.io/)
11 [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
12 [![MIT license](https://img.shields.io/pypi/l/codetiming)](https://mit-license.org/)
13
14 Install `codetiming` from PyPI:
15
16 ```
17 $ python -m pip install codetiming
18 ```
19
20 The source code is [available on GitHub](https://github.com/realpython/codetiming).
21
22 For a complete tutorial on `codetiming`, see [Python Timer Functions: Three Ways to Monitor Your Code](https://realpython.com/python-timer) on [Real Python](https://realpython.com/).
23
24 ## Basic Usage
25
26 You can use `codetiming.Timer` in several different ways:
27
28 1. As a **class**:
29
30 ```python
31 t = Timer(name="class")
32 t.start()
33 # Do something
34 t.stop()
35 ```
36
37 2. As a **context manager**:
38
39 ```python
40 with Timer(name="context manager"):
41 # Do something
42 ```
43
44 3. As a **decorator**:
45
46 ```python
47 @Timer(name="decorator")
48 def stuff():
49 # Do something
50 ```
51
52
53 ## Arguments
54
55 `Timer` accepts the following arguments when it's created. All arguments are optional:
56
57 - **`name`:** An optional name for your timer
58 - **`text`:** The text that's shown when your timer ends. It should contain a `{}` placeholder that will be filled by the elapsed time in seconds (default: `"Elapsed time: {:.4f} seconds"`)
59 - **`initial_text`:** Show text when your timer starts. You may provide the string to be logged or `True` to show the default text `"Timer {name} started"` (default: `False`)
60 - **`logger`:** A function/callable that takes a string argument and will report the elapsed time when the logger is stopped (default: `print()`)
61
62 You can turn off explicit reporting of the elapsed time by setting `logger=None`.
63
64 In the template text, you can also use explicit attributes to refer to the `name` of the timer or log the elapsed time in `milliseconds`, `seconds` (the default), or `minutes`. For example:
65
66 ```python
67 t1 = Timer(name="NamedTimer", text="{name}: {minutes:.1f} minutes")
68 t2 = Timer(text="Elapsed time: {milliseconds:.0f} ms")
69 ```
70
71 Note that the strings used by `text` are **not** f-strings. Instead, they are used as templates that will be populated using `.format()` behind the scenes. If you want to combine the `text` template with an f-string, you need to use double braces for the template values:
72
73 ```python
74 t = Timer(text=f"{__file__}: {{:.4f}}")
75 ```
76
77 `text` is also allowed to be a callable like a function or a class. If `text` is a callable, it is expected to require one argument: the number of seconds elapsed. It should return a text string that will be logged using logger:
78
79 ```python
80 t = Timer(text=lambda secs: f"{secs / 86400:.0f} days")
81 ```
82
83 This allows you to use third-party libraries like [`humanfriendly`](https://pypi.org/project/humanfriendly/) to do the text formatting:
84
85 ```python
86 from humanfriendly import format_timespan
87
88 t1 = Timer(text=format_timespan)
89 t2 = Timer(text=lambda secs: f"Elapsed time: {format_timespan(secs)}")
90 ```
91
92 You may include a text that should be logged when the timer starts by setting `initial_text`:
93
94 ```python
95 t = Timer(initial_text="And so it begins ...")
96 ```
97
98 You can also set `initial_text=True` to use a default initial text.
99
100
101 ## Capturing the Elapsed Time
102
103 When using `Timer` as a class, you can capture the elapsed time when calling `.stop()`:
104
105 ```python
106 elapsed_time = t.stop()
107 ```
108
109 You can also find the last measured elapsed time in the `.last` attribute. The following code will have the same effect as the previous example:
110
111 ```python
112 t.stop()
113 elapsed_time = t.last
114 ```
115
116
117 ## Named Timers
118
119 Named timers are made available in the class dictionary `Timer.timers`. The elapsed time will accumulate if the same name or same timer is used several times. Consider the following example:
120
121 ```pycon
122 >>> import logging
123 >>> from codetiming import Timer
124
125 >>> t = Timer("example", text="Time spent: {:.2f}", logger=logging.warning)
126
127 >>> t.start()
128 >>> t.stop()
129 WARNING:root:Time spent: 3.58
130 3.5836678670002584
131
132 >>> with t:
133 ... _ = list(range(100_000_000))
134 ...
135 WARNING:root:Time spent: 1.73
136
137 >>> Timer.timers
138 {'example': 5.312697440000193}
139 ```
140
141 The example shows how you can redirect the timer output to the logging module. Note that the elapsed time spent in the two different uses of `t` has been accumulated in `Timer.timers`.
142
143 You can also get simple statistics about your named timers. Continuing from the example above:
144
145 ```pycon
146 >>> Timer.timers.max("example")
147 3.5836678670002584
148
149 >>> Timer.timers.mean("example")
150 2.6563487200000964
151
152 >>> Timer.timers.stdev("example")
153 1.311427314335879
154 ```
155
156 `timers` support `.count()`, `.total()`, `.min()`, `.max()`, `.mean()`, `.median()`, and `.stdev()`.
157
158
159 ## Acknowledgments
160
161 `codetiming` is based on a similar module initially developed for the [Midgard Geodesy library](https://kartverket.github.io/midgard/) at the [Norwegian Mapping Authority](https://www.kartverket.no/en/).