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
Spacegit is a .git exposed finder

Spacegit Spacegit is a basic .git exposed finder Usage: You need python3 installed to run spacegit use: python3 spacegit.py (url) Disclaimer: **This i

2 Nov 30, 2021
Finds price floor for every single attribute in a given collection

Solana Solanart Scanner Enjoy the Free Code Steps to run Download VS Code

Dalton Nisbett 19 Oct 20, 2022
A library to easily convert climbing route grades between different grading systems.

pyclimb A library to easily convert climbing route grades between different grading systems. In rock climbing, mountaineering, and other climbing disc

Ilias Antonopoulos 4 Jan 26, 2022
A simple Python app that generates semi-random chord progressions.

chords-generator A simple Python app that generates semi-random chord progressions.

53 Sep 07, 2022
A simple language and reference decompiler/compiler for MHW THK Files

Leviathon A simple language and reference decompiler/compiler for MHW THK Files. Project Goals The project aims to define a language specification for

11 Jan 07, 2023
Python script to get some stats on nodes in a Blender material nodetree

Python script to get some stats on nodes in a Blender material nodetree. It counts the nodes, the node types and the max deep level for group nodes.

Alek Mugnozzo 2 Sep 03, 2022
Helper script to bootstrap a Python environment with the tools required to build and install packages.

python-bootstrap Helper script to bootstrap a Python environment with the tools required to build and install packages. Usage $ python -m bootstrap.bu

Filipe Laíns 7 Oct 06, 2022
🌲 A simple BST (Binary Search Tree) generator written in python

Tree-Traversals (BST) 🌲 A simple BST (Binary Search Tree) generator written in python Installation Use the package manager pip to install BST. Usage

Jan Kupczyk 1 Dec 12, 2021
Protect your eyes from eye strain using this simple and beautiful, yet extensible break reminder

Protect your eyes from eye strain using this simple and beautiful, yet extensible break reminder

Gobinath 1.2k Jan 01, 2023
A collection of common regular expressions bundled with an easy to use interface.

CommonRegex Find all times, dates, links, phone numbers, emails, ip addresses, prices, hex colors, and credit card numbers in a string. We did the har

Madison May 1.5k Dec 31, 2022
The git for the Python Story Utility Package library.

SUP The git for the Python Story Utility Package library. Installation: Install SUP by simply running pip install psup in your terminal. Check out our

Enoki 6 Nov 27, 2022
Napari plugin for loading Bitplane Imaris files .ims

napari-imaris-loader Napari plugin for loading Bitplane Imaris files '.ims'. Notes: For this plugin to work "File/Preferences/Experimental/Render Imag

Alan Watson 4 Dec 01, 2022
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
This code renames subtitle file names to your video files names, so you don't need to rename them manually.

Rename Subtitle This code renames your subtitle file names to your video file names so you don't need to do it manually Note: It only works for series

Mostafa Kazemi 4 Sep 12, 2021
Genart - Generate random art to sell as nfts

Genart - Generate random art to sell as nfts Usage git clone

Will 13 Mar 17, 2022
Deep Difference and search of any Python object/data.

DeepDiff v 5.6.0 DeepDiff Overview DeepDiff: Deep Difference of dictionaries, iterables, strings and other objects. It will recursively look for all t

Sep Dehpour 1.6k Jan 08, 2023
ULID implementation for Python

What is this? This is a port of the original JavaScript ULID implementation to Python. A ULID is a universally unique lexicographically sortable ident

Martin Domke 158 Jan 04, 2023
Adding two matrix from scratch using python.

Adding-two-matrix-from-scratch-using-python. Here, I have take two matrix from user and add it without using any library. I made this program from scr

Sachin Vinayak Dabhade 4 Sep 24, 2021
Experimental python optimistic rollup fraud-proof generation

Macula Experimental python optimistic rollup fraud-proof generation tech by @protolambda. Working on a python version for brevity and simplicity. See

Diederik Loerakker 30 Sep 01, 2022
Script to autocompound 3commas BO:SO based on user provided risk factor

3commas_compounder Script to autocompound 3commas BO:SO based on user provided risk factor Setup Step 1 git clone this repo into your working director

0 Feb 24, 2022