Friday, February 13, 2009

[Python] To raise exception doesn't take extra overhead on call

Hi, it is NISHIO Hirokazu. Today I'll write about Python tips. My friend said "Does a function which raise exceptions take extra overhead on call?" on Twitter. I don't think so, but I wrote a code:


import timeit

print timeit.Timer("foo(1)", setup="""
def foo(x):
if x:
return None
else:
return x
""").repeat()

print timeit.Timer("bar(1)", setup="""
def bar(x):
if x:
return None
else:
raise NotImplementedError
""").repeat()


The formar function doesn't raise any exceptions. The latter does. The timeit module measures time to run given code 1000000 times, and repeat it 3 times. The result is below:


[0.24111700057983398, 0.22863888740539551, 0.22955012321472168]
[0.23151803016662598, 0.23359298706054688, 0.2297508716583252]


I concluded there is no extra overhead between them.

No comments: