Zero runtime impact tracing
Ned Batchelder
ned at nedbatchelder.com
Sat Jul 30 06:13:38 EDT 2016
On Saturday, July 30, 2016 at 4:32:25 AM UTC-4, Johannes Bauer wrote:
> Hi group,
>
> I'm using CPython 3.5.1. Currently I'm writing some delicate code that
> is doing the right thing in 99% of the cases and screws up on the other 1%.
>
> I would like to have tracing in some very inner loops:
>
> if self._debug:
> print("Offset %d foo bar" % (self._offset))
>
> However, this incurs a hefty performance penalty even when tracing disabled.
>
> What I want is that the if clause completely disappears during bytecode
> compilation if self._debug is not set. Is there any way that I can tell
> the optimizer that this variable will either be set once, but never
> change during runtime and that it can go ahead and completely remove the
> code when self._debug is False?
>
> Any other means of signalling the it should compile the tracing code in
> would also be fine by me (e.g, calling Python with some command line
> options or such). As long as during normal operation, there is no
> performance impact.
The __debug__ name is a constant defined by the setting of the -O
command-line switch, and will be compiled away if not true:
https://docs.python.org/3/library/constants.html#__debug__
--Ned.
More information about the Python-list
mailing list