What's the overhead of assertion or debug statements in Python?

Tim Peters tim.peters at gmail.com
Sat Jul 17 02:07:41 EDT 2004


[Daniel Eloff]
> According to the docs, assert() produces no code if optimization is enabled.

That's right.  Note that assert is a statement in Python, not a function.

> My question is, is the same true for
>
> if __debug__:
>            print "Reached this region of code", some_debug_func()
> else:
>            pass

Yes. You won't be wholly comfortable with what I'm about to show you
until you have more Python experience, but Python always gives you a
way to answer any question you have (about Python, or anything else
<wink>):

C:\Code>type example.py
def f():
    if __debug__:
        print "some stuff"
    else:
        pass

C:\Code>\python23\python.exe
Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> import dis
>>> dis.dis(example.f)
  2           0 LOAD_GLOBAL              0 (__debug__)
              3 JUMP_IF_FALSE            9 (to 15)
              6 POP_TOP

  3           7 LOAD_CONST               1 ('some stuff')
             10 PRINT_ITEM
             11 PRINT_NEWLINE
             12 JUMP_FORWARD             1 (to 16)
        >>   15 POP_TOP

  5     >>   16 LOAD_CONST               0 (None)
             19 RETURN_VALUE
>>> 


C:\Code>\python23\python.exe -O
Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> import dis
>>> dis.dis(example.f)
  5           0 LOAD_CONST               0 (None)
              3 RETURN_VALUE
>>>

Those showed the Python Virtual Machine (PVM) instructions generated
for the example function, without and with optimization, respectively.
 You don't have to know a lot about the PVM to see that very little is
generated in the latter case.

> Is there any overhead associated with this at runtime?

Yes in non-optimized mode, no in optimized mode.

> Any branching or run time evaluation of the value of __debug__?

Same as the last answer.

> I'm trying to discover if I can litter my code with debug stuff, or if I should go
> sparingly in performance critical code like some innermost loops.
>
> Also, how can I enable and disable optimization?

Do or don't pass -O on the Python command line, respectively.  Note
that, for speed, Python generates persistent compiled code files the
first time you import a Python module in a given mode:  .pyc files are
debug-mode compiled code, and .pyo files are optimized-mode compiled
code.  You don't have to tell Python to generate these, it does it
automatically (and automatically rebuilds them if you change a code
file).



More information about the Python-list mailing list