• Stars
    star
    273
  • Rank 150,780 (Top 3 %)
  • Language
    Python
  • License
    MIT License
  • Created over 5 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A flexible, customizable timer for your Python code

Python Timer Functions: Three Ways to Monitor Your Code

codetiming - A flexible, customizable timer for your Python code

Latest version Python versions Downloads Tests Checked with mypy Interrogate DocStrings Code style: black MIT license

Install codetiming from PyPI:

$ python -m pip install codetiming

The source code is available on GitHub.

For a complete tutorial on codetiming, see Python Timer Functions: Three Ways to Monitor Your Code on Real Python.

Basic Usage

You can use codetiming.Timer in several different ways:

  1. As a class:

    t = Timer(name="class")
    t.start()
    # Do something
    t.stop()
  2. As a context manager:

    with Timer(name="context manager"):
        # Do something
  3. As a decorator:

    @Timer(name="decorator")
    def stuff():
        # Do something

Arguments

Timer accepts the following arguments when it's created. All arguments are optional:

  • name: An optional name for your timer
  • 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")
  • 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)
  • logger: A function/callable that takes a string argument and will report the elapsed time when the logger is stopped (default: print())

You can turn off explicit reporting of the elapsed time by setting logger=None.

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:

t1 = Timer(name="NamedTimer", text="{name}: {minutes:.1f} minutes")
t2 = Timer(text="Elapsed time: {milliseconds:.0f} ms")

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:

t = Timer(text=f"{__file__}: {{:.4f}}")

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:

t = Timer(text=lambda secs: f"{secs / 86400:.0f} days")

This allows you to use third-party libraries like humanfriendly to do the text formatting:

from humanfriendly import format_timespan

t1 = Timer(text=format_timespan)
t2 = Timer(text=lambda secs: f"Elapsed time: {format_timespan(secs)}")

You may include a text that should be logged when the timer starts by setting initial_text:

t = Timer(initial_text="And so it begins ...")

You can also set initial_text=True to use a default initial text.

Capturing the Elapsed Time

When using Timer as a class, you can capture the elapsed time when calling .stop():

elapsed_time = t.stop()

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:

t.stop()
elapsed_time = t.last

Named Timers

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:

>>> import logging
>>> from codetiming import Timer

>>> t = Timer("example", text="Time spent: {:.2f}", logger=logging.warning)

>>> t.start()
>>> t.stop()
WARNING:root:Time spent: 3.58
3.5836678670002584

>>> with t:
...     _ = list(range(100_000_000))
... 
WARNING:root:Time spent: 1.73

>>> Timer.timers
{'example': 5.312697440000193}

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.

You can also get simple statistics about your named timers. Continuing from the example above:

>>> Timer.timers.max("example")
3.5836678670002584

>>> Timer.timers.mean("example")
2.6563487200000964

>>> Timer.timers.stdev("example")
1.311427314335879

timers support .count(), .total(), .min(), .max(), .mean(), .median(), and .stdev().

Acknowledgments

codetiming is based on a similar module initially developed for the Midgard Geodesy library at the Norwegian Mapping Authority.

More Repositories

1

python-guide

Python best practices guidebook, written for humans.
Batchfile
28,040
star
2

discover-flask

Full Stack Web Development with Flask.
Python
4,513
star
3

materials

Bonus materials, exercises, and example projects for our Python tutorials
HTML
4,357
star
4

python-scripts

because i'm tired of gists
Python
2,050
star
5

list-of-python-api-wrappers

List of Python API Wrappers and Libraries
2,003
star
6

flask-boilerplate

Boilerplate template for a Python Flask application with Flask-SQLAlchemy, Flask-WTF, Fabric, Coverage, and Bootstrap
Python
1,425
star
7

dockerizing-django

Python
1,324
star
8

python-basics-exercises

Python Basics: A Practical Introduction to Python 3
Python
953
star
9

flask-by-example

flask, heroku, environment variables, sqlalchemy, flask-migrate, redis
Python
678
star
10

orchestrating-docker

Python
464
star
11

cookiecutter-flask-skeleton

Real Python Flask Starter Project
Python
431
star
12

flask-jwt-auth

just testing some jwts
Python
276
star
13

ultimate-flask-front-end

blog post
JavaScript
253
star
14

pytest-mypy

Mypy static type checker plugin for Pytest
Python
247
star
15

python-speech-recognition

Speech Recognition with Python examples
Python
224
star
16

realpython-blog

real python blog posts
Python
198
star
17

django-slow-tests

Locate your slowest tests.
Python
178
star
18

book2-exercises

Book 2 -- Exercises for the book
Python
165
star
19

stack-spider

Python
164
star
20

book1-exercises

Book 1 -- Exercises for the book
Python
161
star
21

flask-single-page-app

HTML
158
star
22

Picha

Simple Django App That Gets Photos from Flickr Public Feeds
Python
152
star
23

twitter-sentiment-elasticsearch

Let's perform Twitter sentiment analysis using Python, Docker, Elasticsearch, and Kibana!
Python
133
star
24

flask-deploy

Check out the blog post:
Python
132
star
25

image-fingerprinting

Python
127
star
26

django-form-fun

model forms, ajax
Python
127
star
27

reader

Read the latest Real Python tutorials (PyPI Demo Package)
Python
122
star
28

flask-registration

Python
101
star
29

django-example-channels

Python
98
star
30

book3-exercises

Book 3 Advanced Web Dev with Django 1.7 -- Exercises for the book
Python
89
star
31

flask-scaffold

Python
67
star
32

flask-bokeh-example

Python
65
star
33

flask-angular-auth

Handling User Authentication With Angular and Flask
JavaScript
65
star
34

about

testimonials, table of contents, changelog, etc.
Python
62
star
35

pygame-primer

Python
56
star
36

web-dev-for-data-scientists

Python
52
star
37

django-puppy-store

Python
49
star
38

flask-stock-visualizer

JavaScript
48
star
39

python-web-scraping-examples

Python
42
star
40

rptree

Directory Tree Generator
Python
42
star
41

learning

40
star
42

flask-paywall

Setup a paywall with Flask and Stripe to offer paid access to your premium content.
Python
39
star
43

flask-image-search

Python
37
star
44

image-of-the-day

Example application for beanstalk deployment blog
Python
36
star
45

fitter-happier-docker

Python
33
star
46

automated-deployments

Python
33
star
47

interview-questions

Python
31
star
48

django-redis-cache

Python
29
star
49

angular4-auth

jwt auth with angular 4
TypeScript
29
star
50

data-version-control

Python
26
star
51

python-mocks

Python
21
star
52

django_cookiecutter_docker

blog post
Python
20
star
53

support

Please contact us at →
19
star
54

django-social-auth-example

Adding Social Authentication to Django
Python
18
star
55

flask-docker-workflow

Python
18
star
56

flask-bitcoin-example

Python
15
star
57

django-receipts

Python
12
star
58

flask-docker

Python
11
star
59

python-social-auth

Python
11
star
60

python-ruby-golang

comparing python, ruby, and golang
Go
10
star
61

robocrop

Your friendly neighbourhood image resizing API
Python
10
star
62

flask-matplotlib

render matplotlib images in flask (sample)
Python
10
star
63

flasktaskr_project

Python
10
star
64

aws-lambda-code-execute

HTML
9
star
65

python-mock-server

Python
9
star
66

instagram-analyzer

Python
7
star
67

django_cookiecutter_fedora

blog post
Python
7
star
68

flask-download

wip
Python
6
star
69

django-bootstrap

Python
6
star
70

mount-olympus

Mount Olympus web scraping example app
HTML
6
star
71

flask-sinatra-martini

https://realpython.com/blog/python/python-ruby-and-golang-a-web-Service-application-comparison/
Shell
5
star
72

lms

Python
5
star
73

flask-messaging

Python
5
star
74

members-map

Real Python Community Members Map
Python
5
star
75

python-mock-example

Python
5
star
76

members

learning management system for real python
JavaScript
5
star
77

pygments-redis

Pygments highlighter for Redis CLI
Python
5
star
78

django-docker-tests

Python
4
star
79

sales-metrics

Python
4
star
80

vscode-theme

Real Python Visual Studio Code Theme
4
star
81

django-docker-workflow

Python
4
star
82

data-repos

Python
4
star
83

author-tools

VS Code extension with a set of tools to help Real Python authors
TypeScript
4
star
84

pygments-httpie

A Pygments lexer for the the output of httpie
Python
3
star
85

flask-ansible

Python
3
star
86

pizzaup

JavaScript
3
star
87

realpython-intro

3
star
88

fullscalepython-app

Python
3
star
89

python-slack-api

Python
3
star
90

docker-hook-listener

Python
3
star
91

python-and-mongo

Python
2
star
92

docker_polls_project

Python
2
star
93

task-exceptions

Python
2
star
94

react-intro

JavaScript
2
star
95

gh-download

Download source code for specific Real Python tutorials
JavaScript
2
star
96

daily-commit

wip
Python
2
star
97

ecological-footprint

A web map that displays ecological footprint per capita, created with Python's folium library
HTML
2
star
98

python-driven-web-applications

1
star
99

fake-jobs

A Fake Python job board for your Real Python web scraping training
HTML
1
star
100

serializer

1
star