ticktock is a minimalist library to view Python time performance of Python code.

Overview

ticktock

Simple Python code metering library.


ticktock is a minimalist library to view Python time performance of Python code.

First, install ticktock:

pip install py-ticktock

Then, anywhere in your code you can use tick to start a clock, and tock to register the end of the snippet you want to time:

t = tick()
# do some work
t.tock()

Even if the code is called many times within a loop, measured times will only periodially (2 seconds by default):

import time
from ticktock import tick

for _ in range(1000):
    t = tick()
    # do some work
    time.sleep(1)
    t.tock()

You can create multiple independent ticks, which will appear as two separate clocks:

for _ in range(1000):
    t = tick()
    # do some work
    time.sleep(1)
    t.tock()

    t = tick()
    # do some other work
    time.sleep(0.5)
    t.tock()

Ticks can share a common starting point:

for k in range(1000):
    t = tick()
    # do some work
    time.sleep(1)
    if k % 2 == 1:
        time.sleep(1)
        t.tock()
    else:
        t.tock()

It is also possible to use ticktock as a context manager to track the timing of a chunk of code:

from ticktock import ticktock

with ticktock():
    time.sleep(1)

Or a decorator, to track the timing of each call to a function:

from ticktock import ticktock

@ticktock
def f():
    time.sleep(1)

f()
Comments
  • feature request: suspended mode

    feature request: suspended mode

    Hi,

    I could not find in documentation: is there a way of temporarily shutting off all ticktock calls? This is helpful for switching between debug and production modes.

    Thanks!

    opened by gilbh 8
  • Suppress line numbers in `tock()`

    Suppress line numbers in `tock()`

    Hello.

    Thanks for your effort on the library, works really nice.

    I would like to polish the output a bit - i.e. suppress the line numbers from the tock event, since In some cases they are redundant. For a :

    @ticktick("aaa")
    def a():
       pass
    

    I want: [aaaa] 1s200 ms and now I have [aaaa:3-5] 1s200 ms

    And for a:

    a_clock = tick(name="train batch")
    a_clock.tock()
    

    I want: [train batch] 100ms and now I get [train batch:11] 100ms

    Rationale: In the annotation case - this is obvious that a method with decorator will just get a single tock() for every tick - and so there is no need to differentiate the times, and hence it would be best if the output shown would just contain the name passed to @ticktock()

    In the manual case - I would say, that this should be user-controlled. I am not sure what the API would be best, but maybe something like tick(single_tock=True) or tock(only=True) that would made the tock() not record any name for the tock and therefore the ouptut might just contain the name passed to tick ?

    opened by kretes 5
  • feature request: easier control on renderer

    feature request: easier control on renderer

    Hi,

    I noticed there is no carriage return in the ticktock message, so I wrote the following, but I was wondering if there could be a less verbose way of doing this:

    from ticktock import ticktock
    from ticktock.timer import ClockCollection, set_collection
    from ticktock import renderers
    
    set_collection(
        collection=ClockCollection(renderer=renderers.StandardRenderer(format=renderers.StandardRenderer()._format + '\n')))
    
    
    @ticktock
    def test():
        for aa in range(100_000):
            pass
    
    
    test()
    print('done')
    

    Thanks!

    opened by gilbh 5
  • bug: ImportError: cannot import name 'ticktock' from 'ticktock'

    bug: ImportError: cannot import name 'ticktock' from 'ticktock'

    Hi,

    Maybe it's something I don't get, but I can't get pass the import statement:

    ImportError: cannot import name 'ticktock' from 'ticktock' (c:\users\gil\envs\utils\lib\site-packages\ticktock.py)
    > c:\dropbox\documents_and_writings\research\digital_humanities\python\stocks\trade_ampf.py(34)<module>()
         32 from shutil import copyfile
         33 from itertools import repeat
    ---> 34 from ticktock import ticktock
    

    The pip install went fine....

    Running on Windows ...

    Thanks!

    opened by gilbh 1
  • Fix name

    Fix name

    This fixes a bug encountered when using ticktock in a REPL with unnamed tick calls.

    In this context, clock.tick_filename does not exist, and name_field_fn fails because tick_name is used before being defined. This was broken recently.

    The first commit adds a test to expose the bug, while the second fixes it.

    opened by victorbenichoux 0
  • Renderer per clock + fix to decorator and context manager + refacto

    Renderer per clock + fix to decorator and context manager + refacto

    This PR is relatively large, and achieves the following:

    • Add the capability to have different formatting strings for different clocks, which adresses the requests in https://github.com/victorbenichoux/ticktock/issues/12 as well as https://github.com/victorbenichoux/ticktock/issues/4
    • Simplifies the format string, with a general name field that works in decorators/context managers as one would expect
    • Refactor by splitting ticktock.timer into ticktock.clocks with clocks, ticktock.collection with collection, ticktock.timers for decorator/contextmanager interfaces
    • Refactor by removing largely unused Clock and tick parameters (e.g. tick_time_ns)
    • Make clock identity consistent by never disambiguating clocks on their names
    • Better tests of context manager and function decorator functionality
    • numerous improvements to the documentation
    opened by victorbenichoux 0
  • More formatting options

    More formatting options

    This PR introduces more formatting options, by enabling the user to choose amongst more keys, for example the tick line, tock line, but also the raw timings.

    This added flexibility adds a bit more constraints: in particular, format strings should also contain the clock name part:

    set_format("⏱️ [{tick_name}-{tock_name}] {mean} ({std} std) min={min} max={max} count={count} last={last}")
    

    There are also a couple of minor refactorizations.

    opened by victorbenichoux 0
  • Set formatting

    Set formatting

    • Add a global set_format function to set the format of ticktock messages
    • Allow setting max_terms through set_format (https://github.com/victorbenichoux/ticktock/issues/4)
    • Create a no_update flag in StandardRenderer to avoid print ASCII control chars
    opened by victorbenichoux 0
  • Default two precision

    Default two precision

    This PR fixes https://github.com/victorbenichoux/ticktock/issues/6 by adding another level of precision to the times that are shown by the StandardRenderer.

    This can be controlled by setting max_terms on the StandardRenderer, which defaults to 2.

    opened by victorbenichoux 0
  • MultipleRenderers - delegates rendering to multiple renderers

    MultipleRenderers - delegates rendering to multiple renderers

    This is a small facade over renderers that we use for e.g. render at the same time to stdout and to external monitoring system. It would be nice to have it in the library

    opened by kretes 2
  • Allow to configure the behaviour of StandardRenderer

    Allow to configure the behaviour of StandardRenderer

    Currently we use StandardRenderer with no_update=True and it is used in a process that uses tqdm (keras training loop). The effect is that the first line from ticktock is appended at the end of the line of current tqdm progress. I can see in https://github.com/victorbenichoux/ticktock/blob/main/ticktock/std.py#L137 there is a new line appended at the end of ticktock output. We would like to add a new line at the beginning as well. WDYT of either including it be default or allowing to customize it by the client?

    opened by kretes 1
Releases(v0.1.0)
  • v0.1.0(Nov 19, 2021)

    This is the first minor release of ticktock. It contains many bug fixes and a major overhaul of the formatting system.

    • The format string now can control the whole output line (including the beginning of the line with the name). Format can be set globally with set_format.
    • Providing a format=... keyword argument to any of the ticktock functions (decorator, context manager, tick/tock) will override the formatting for this clock.
    • Format strings now accept a generic name parameter that takes into account the provided name parameters to ticktock functions, and has a consistent behavior across use cases
    • tick returns a Clock instance, while tock returns the recorded time delta in ns
    • clock disambiguation now exclusively occurs with frame information (also used names previously)
    • Internal modules have been reorganized: ticktock.renderers has been split into ticktock.renderers and ticktock.std , ticktock.timer has been split in ticktock.clocks, ticktock.collection and ticktock.timers
    Source code(tar.gz)
    Source code(zip)
  • v0.0.7(Nov 14, 2021)

    Easier control on formatting: use set_format(format: str, max_terms: int = None, no_update: bool) to set:

    • the format string format
    • the number of displayed units it times max_terms (https://github.com/victorbenichoux/ticktock/issues/6)
    • and to turn off ASCII control characters (used to update the previous line) with no_update This was signaled by https://github.com/victorbenichoux/ticktock/issues/4.

    Turn on or off the ticktock collection of timings and rendering with enable/disable. (https://github.com/victorbenichoux/ticktock/issues/5)

    Fix a bug in which the carriage return was not returned.

    Improvements to the documentation, some more testing.

    Thanks to all the people who contributed issues!

    Source code(tar.gz)
    Source code(zip)
Owner
Victor Benichoux
Principal data scientist/ex- computational neuroscientist
Victor Benichoux
SysInfo is an app developed in python which gives Basic System Info , and some detailed graphs of system performance .

SysInfo SysInfo is an app developed in python which gives Basic System Info , and some detailed graphs of system performance . Installation Download t

null 5 Nov 8, 2021
Lark is a parsing toolkit for Python, built with a focus on ergonomics, performance and modularity.

Lark is a parsing toolkit for Python, built with a focus on ergonomics, performance and modularity.

Lark - Parsing Library & Toolkit 3.5k Jan 5, 2023
Fcpy: A Python package for high performance, fast convergence and high precision numerical fractional calculus computing.

Fcpy: A Python package for high performance, fast convergence and high precision numerical fractional calculus computing.

SciFracX 1 Mar 23, 2022
This is discord nitro code generator and checker made with python. This will generate nitro codes and checks if the code is valid or not. If code is valid then it will print the code leaving 2 lines and if not then it will print '*'.

Discord Nitro Generator And Checker ⚙️ Rᴜɴ Oɴ Rᴇᴘʟɪᴛ ??️ Lᴀɴɢᴜᴀɢᴇs Aɴᴅ Tᴏᴏʟs If you are taking code from this repository without a fork, then atleast

Vɪɴᴀʏᴀᴋ Pᴀɴᴅᴇʏ 37 Jan 7, 2023
Python implementation of Gorilla time series compression

Gorilla Time Series Compression This is an implementation (with some adaptations) of the compression algorithm described in section 4.1 (Time series c

Ghiles Meddour 19 Jan 1, 2023
Edit SRT files to delay subtitle time-stamps.

subtitle-delay A program written in Python that directly edits SRT file to delay the subtitles. Features: Will throw an error if delaying with negativ

null 8 Jul 17, 2022
Simple integer-valued time series bit packing

Smahat allows to encode a sequence of integer values using a fixed (for all values) number of bits but minimal with regards to the data range. For example: for a series of boolean values only one bit is needed, for a series of integer percentages 7 bits are needed, etc.

Ghiles Meddour 7 Aug 27, 2021
Conveniently measures the time of your loops, contexts and functions.

Conveniently measures the time of your loops, contexts and functions.

Maciej J Mikulski 79 Nov 15, 2022
A time table app to notify the user about their class timings

kivyTimeTable A time table app to notify the user about their class timings Features This project incorporates some features i wanted to see in a time

null 2 Dec 15, 2021
Gradually automate your procedures, one step at a time

Gradualist Gradually automate your procedures, one step at a time Inspired by https://blog.danslimmon.com/2019/07/15/ Features Main Features Converts

Ross Jacobs 8 Jul 24, 2022
New time-based UUID formats which are suited for use as a database key

uuid6 New time-based UUID formats which are suited for use as a database key. This module extends immutable UUID objects (the UUID class) with the fun

null 26 Dec 30, 2022
UUID version 7, which are time-sortable (following the Peabody RFC4122 draft)

uuid7 - time-sortable UUIDs This module implements the version 7 UUIDs, proposed by Peabody and Davis in https://www.ietf.org/id/draft-peabody-dispatc

Steve Simmons 22 Dec 20, 2022
Compute the fair market value (FMV) of staking rewards at time of receipt.

tendermint-tax A tool to help calculate the tax liability of staking rewards on Tendermint chains. Specifically, this tool calculates the fair market

null 5 Jan 7, 2022
A functional standard library for Python.

Toolz A set of utility functions for iterators, functions, and dictionaries. See the PyToolz documentation at https://toolz.readthedocs.io LICENSE New

null 4.1k Dec 30, 2022
🔩 Like builtins, but boltons. 250+ constructs, recipes, and snippets which extend (and rely on nothing but) the Python standard library. Nothing like Michael Bolton.

Boltons boltons should be builtins. Boltons is a set of over 230 BSD-licensed, pure-Python utilities in the same spirit as — and yet conspicuously mis

Mahmoud Hashemi 6k Jan 4, 2023
Retrying library for Python

Tenacity Tenacity is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just

Julien Danjou 4.3k Jan 5, 2023
Retrying is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just about anything.

Retrying Retrying is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just

Ray Holder 1.9k Dec 29, 2022
isort is a Python utility / library to sort imports alphabetically, and automatically separated into sections and by type.

isort is a Python utility / library to sort imports alphabetically, and automatically separated into sections and by type. It provides a command line utility, Python library and plugins for various editors to quickly sort all your imports.

Python Code Quality Authority 5.5k Jan 8, 2023
A Python library for reading, writing and visualizing the OMEGA Format

A Python library for reading, writing and visualizing the OMEGA Format, targeted towards storing reference and perception data in the automotive context on an object list basis with a focus on an urban use case.

Institut für Kraftfahrzeuge, RWTH Aachen, ika 12 Sep 1, 2022