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
The uncompromising Python code formatter

The Uncompromising Code Formatter “Any color you like.” Black is the uncompromising Python code formatter. By using it, you agree to cede control over

Python Software Foundation 30.7k Dec 28, 2022
The strictest and most opinionated python linter ever!

wemake-python-styleguide Welcome to the strictest and most opinionated python linter ever. wemake-python-styleguide is actually a flake8 plugin with s

wemake.services 2.1k Jan 05, 2023
A static analysis tool for Python

pyanalyze Pyanalyze is a tool for programmatically detecting common mistakes in Python code, such as references to undefined variables and some catego

Quora 212 Jan 07, 2023
Run-time type checker for Python

This library provides run-time type checking for functions defined with PEP 484 argument (and return) type annotations. Four principal ways to do type

Alex Grönholm 1.1k Dec 19, 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
fixup: Automatically add and remove python import statements

fixup: Automatically add and remove python import statements The goal is that running fixup my_file.py will automatically add or remove import stateme

2 May 08, 2022
CodeAnalysis - Static Code Analysis: a code comprehensive analysis platform

TCA, Tencent Cloud Code Analysis English | 简体中文 What is TCA Tencent Cloud Code A

Tencent 1.3k Jan 07, 2023
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
Optional static typing for Python 3 and 2 (PEP 484)

Mypy: Optional Static Typing for Python Got a question? Join us on Gitter! We don't have a mailing list; but we are always happy to answer questions o

Python 14.4k Jan 05, 2023
Auto-generate PEP-484 annotations

PyAnnotate: Auto-generate PEP-484 annotations Insert annotations into your source code based on call arguments and return types observed at runtime. F

Dropbox 1.4k Dec 26, 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
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
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
A system for Python that generates static type annotations by collecting runtime types

MonkeyType MonkeyType collects runtime types of function arguments and return values, and can automatically generate stub files or even add draft type

Instagram 4.1k Jan 02, 2023
An analysis tool for Python that blurs the line between testing and type systems.

CrossHair An analysis tool for Python that blurs the line between testing and type systems. THE LATEST NEWS: Check out the new crosshair cover command

Phillip Schanely 836 Jan 08, 2023
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
Data parsing and validation using Python type hints

pydantic Data validation and settings management using Python type hinting. Fast and extensible, pydantic plays nicely with your linters/IDE/brain. De

Samuel Colvin 12.1k Jan 05, 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
Static type checker for Python

Static type checker for Python Speed Pyright is a fast type checker meant for large Python source bases. It can run in a “watch” mode and performs fas

Microsoft 9.4k Jan 07, 2023
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