On Mon, Nov 30, 2020 at 12:11:01AM +0100, Marco Sulla wrote:

> You can get the code of a function as a string using `inspect`.

*Sometimes*.


    >>> import inspect
    >>> def func():
    ...     return 1
    ... 
    >>> inspect.getsource(func)
    Traceback (most recent call last):
      [...]
    OSError: could not get source code



I have been using a variant of this for years now:


https://code.activestate.com/recipes/577896-benchmark-code-with-the-with-statement/


It's not suitable for timing microbenchmarks, since the overhead of the 
with statement could be greater than the code you are timing, but 
sometimes you want a quick time measurement for something, and this is 
much better than

    import time
    t = time.time()
    # run code here
    t = time.time() - t

*especially* when you're typing code in the interactive interpreter.


-- 
Steve
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/ANIJLXDFQ4KZMWRYEG4URN4VMQ4UAJ5D/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to