control structures (was "Re: Sins")

Neel Krishnaswami neelk at brick.cswv.com
Thu Jan 6 19:37:29 EST 2000


Darrell <darrell at dorb.com> wrote:
> From: "Skip Montanaro"
> >
> > I find nothing wrong with it.  Some people object to using try/except for
> > anything but handling errors however.
> 
> Don't know if this if fair. But exceptions are slow when raised.

Random question: why?

When I tried timing a dummy loop with 100,000 exceptions versus 100K
function calls, I found that the exceptions took roughly 3 times
longer. (On CPython 1.5.2)

This doesn't make a whole lot of sense to me. The exceptions shouldn't
have to create new stack frames, it just has to deallocate an old one
and climb back up the stack. The function call should create a new
stack frame, deallocate it, and then climb back up the stack.

A quick examination of the source doesn't seem to disabuse me of this
notion (except some stack frames are saved), but that would seem to
affect function calls and exceptions more or less equally. Is it
because the function calling code is inlined into eval_code_loop() and
do_raise() isn't?

The code:

  def exception_test():
    r = range(100000)
    t1 = time.time()
    for i in r:
      try:
  	raise "Error"
      except:
  	pass
    t2 = time.time()
    return t2 - t1

Median of 5 runs: 1.7
  
  def call_test():
    r = range(100000)
    f = lambda: 3
    t1 = time.time()
    for i in r:
      f()
    t2 = time.time()
    return t2 - t1

Median of 5 runs: 0.45


Neel



More information about the Python-list mailing list