Skip to main content

Simple Python Timer class you can wrap around blocks of code you want to benchmark

Project description



WithTimer is a Python module for benchmarking your code. It has the following features:

  • Simple use
    • Just create a timer object, and it times execution until it goes out of scope
  • Arbitrarily nested timers
    • Create as many nested timers as you want
    • Each timer pushes itself to a stack, and pops itself off when destroyed

Example usage

with Timer(name="Something slow"):

Timing is turned off by default, and can be optionally turned on. You can instrument your code with timers, and leave them in when you're not using them:

if args.enable_timing:
with Timer(name="Timers are a sometimes treat"):

You can nest timers:

with Timer(name="Outer timer"):
  for i in range(0, 100000):
    with Timer(name="Hope this isn't O(n^2)"):

Here's a complete example:

from time import sleep
from withtimer.withtimer import Timer

def func1(count):
    for i in range(0, 3):
        with Timer(name="Calling func2"):
    print("func1 sleeping {}".format(count))

def func2(count):
    print("func2 sleeping {}".format(count))

if __name__ == "__main__":
    with Timer(name="main"):
        for i in range(0, 3):
            if i % 2 > 0:


$ python3  ./
[main] start
    [Calling func2] start
func2 sleeping 2
    [Calling func2] end	Elapsed time: 2.003 seconds

    [Calling func2] start
func2 sleeping 2
    [Calling func2] end	Elapsed time: 2.003 seconds

    [Calling func2] start
func2 sleeping 2
    [Calling func2] end	Elapsed time: 2.003 seconds

func1 sleeping 2
[main] end	Elapsed time: 8.015 seconds

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for withtimer, version 0.1.0.dev1
Filename, size File type Python version Upload date Hashes
Filename, size withtimer-0.1.0.dev1-py3-none-any.whl (5.0 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size withtimer-0.1.0.dev1.tar.gz (3.3 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page