ticktock is a minimalist library to profile Python code

Related tags

Code Analysisticktock
Overview

ticktock

Simple Python code metering library.


ticktock is a minimalist library to profile Python code: it periodically displays timing of running code.

Quickstart

First, install ticktock:

pip install py-ticktock

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:

from ticktock import tick

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

This will print:

⏱️ [3-5] 50us count=1

Indicating that lines 3-5 took <50us to run.

You can use ticktock arbitrarily deep inside you Python code and still get meaningful timing information.

When the timer is called multiple times (for example within a loop), measured times will be aggregated and printed periodically (every 2 seconds by default).

As a result, the following code:

from ticktock import tick

for _ in range(1000):
    clock = tick()
    # do some work
    clock.tock()

Will output:

⏱️ [4-6] 50us count=1000

ticktock acts as a context manager to track the timing of a chunk of code:

from ticktock import ticktock

with ticktock():
    time.sleep(1)

Or as a decorator:

from ticktock import ticktock

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

Checkout the documentation for a complete manual!

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
Machine learning (especially NLP), formerly computational neuroscience
Victor Benichoux
Inspects Python source files and provides information about type and location of classes, methods etc

prospector About Prospector is a tool to analyse Python code and output information about errors, potential problems, convention violations and comple

Python Code Quality Authority 1.7k Dec 31, 2022
An interpreter for the X1 bytecode.

X1 Bytecode Interpreter The X1 Bytecode is bytecode designed for simplicity in programming design and compilation. Bytecode Instructions push

Thanasis Tzimas 1 Jan 15, 2022
C/C++ Dependency Analyzer: a rewrite of John Lakos' dep_utils (adep/cdep/ldep) from

Version bêta d'un système pour suivre les prix des livres chez Books to Scrape, un revendeur de livres en ligne. En pratique, dans cette version bêta, le programme n'effectuera pas une véritable surv

Olzhas Rakhimov 125 Sep 21, 2022
Turn your Python and Javascript code into DOT flowcharts

Notes from 2017 This is an older project which I am no longer working on. It was built before ES6 existed and before Python 3 had much usage. While it

Scott Rogowski 3k Jan 09, 2023
A static type analyzer for Python code

pytype - ? ✔ Pytype checks and infers types for your Python code - without requiring type annotations. Pytype can: Lint plain Python code, flagging c

Google 4k Dec 31, 2022
A formatter for Python files

YAPF Introduction Most of the current formatters for Python --- e.g., autopep8, and pep8ify --- are made to remove lint errors from code. This has som

Google 13k Dec 31, 2022
pycallgraph is a Python module that creates call graphs for Python programs.

Project Abandoned Many apologies. I've stopped maintaining this project due to personal time constraints. Blog post with more information. I'm happy t

gak 1.7k Jan 01, 2023
Typing-toolbox for Python 3 _and_ 2.7 w.r.t. PEP 484.

Welcome to the pytypes project pytypes is a typing toolbox w.r.t. PEP 484 (PEP 526 on the road map, later also 544 if it gets accepted). Its main feat

Stefan Richthofer 188 Dec 29, 2022
A very minimalistic python module that lets you track the time your code snippets take to run.

Clock Keeper A very minimalistic python module that lets you track the time your code snippets take to run. This package is available on PyPI! Run the

Rajdeep Biswas 1 Jan 19, 2022
Metrinome is an all-purpose tool for working with code complexity metrics.

Overview Metrinome is an all-purpose tool for working with code complexity metrics. It can be used as both a REPL and API, and includes: Converters to

26 Dec 26, 2022
ticktock is a minimalist library to profile Python code

ticktock is a minimalist library to profile Python code: it periodically displays timing of running code.

Victor Benichoux 30 Sep 28, 2022
A Python utility / library to sort imports.

Read Latest Documentation - Browse GitHub Code Repository isort your imports, so you don't have to. isort is a Python utility / library to sort import

Python Code Quality Authority 5.5k Jan 06, 2023
An app to show the total number of lines of code written by an user.

Lines of code Have you ever wondered how many lines of code you wrote in github? This tool will calculate it for you! To calculate the total number of

B.Jothin kumar 10 Jan 26, 2022
Collects all accepted (partial and full scored) codes submitted within the given timeframe and saves them locally for plagiarism check.

Collects all accepted (partial and full scored) codes submitted within the given timeframe of any contest.

ARITRA BELEL 2 Dec 28, 2021
Pymwp is a tool for automatically performing static analysis on programs written in C

pymwp: MWP analysis in Python pymwp is a tool for automatically performing static analysis on programs written in C, inspired by "A Flow Calculus of m

Static Analyses of Program Flows: Types and Certificate for Complexity 2 Dec 02, 2022
Collection of library stubs for Python, with static types

typeshed About Typeshed contains external type annotations for the Python standard library and Python builtins, as well as third party packages as con

Python 3.3k Jan 02, 2023
This is a Python program to get the source lines of code (SLOC) count for a given GitHub repository.

This is a Python program to get the source lines of code (SLOC) count for a given GitHub repository.

Nipuna Weerasekara 2 Mar 10, 2022
A simple stopwatch for measuring code performance with static typing.

A simple stopwatch for measuring code performance. This is a fork from python-stopwatch, which adds static typing and a few other things.

Rafael 2 Feb 18, 2022
Alarmer is a tool focus on error reporting for your application.

alarmer Alarmer is a tool focus on error reporting for your application. Installation pip install alarmer Usage It's simple to integrate alarmer in yo

long2ice 20 Jul 03, 2022
A bytecode vm written in python.

CHex A bytecode vm written in python. hex command meaning note: the first two hex values of a CHex program are the magic number 0x01 (offset in memory

1 Aug 26, 2022