Python speed testing -- why does an except failure cost so much time -


i assumed try / except workflow faster if / workflow simple action 'try remove x list_l'. in below example, except failures (x not in list_l) cost more times permission requests (if x in list_l) though there chance of exception 16.6% of time. why?

here tests coded , results:

import random, time, timeit  class timer(object):     def __enter__(self):         self.start = time.time()         return self      def __exit__(self, *args):         self.end = time.time()         self.secs = self.end - self.start         self.msecs = self.secs * 1000  # millisecs  def a_function():     a_list = list(xrange(10))     choice_list = list(xrange(12))     choice = random.choice(choice_list)     try:         a_list.remove(choice)      except valueerror:         pass  def b_function():     a_list = list(xrange(10))     choice_list = list(xrange(12))     choice = random.choice(choice_list)     if choice in a_list:         a_list.remove(choice)  timer() a:     print('test_a', timeit.timeit("a_function()", number=10000, setup="from __main__ import a_function"))  timer() b:     print('test_b', timeit.timeit("b_function()", number=10000, setup="from __main__ import b_function")) 

the results:

1st attempt: ('test_a', 0.029724836349487305)('test_b', 0.027068138122558594)

2nd attempt: ('test_a', 0.02960801124572754)('test_b', 0.026785850524902344)

3rd attempt: ('test_a', 0.029654979705810547)('test_b', 0.02665996551513672)

also, if increase choice_list range 20, difference widens because exceptions occur more frequently. if python ask-forgiveness-not-permission, why failure seem cost in terms of time?

exceptions expensive in language, , misuse of them.

exceptions meant exceptional circumstances code cannot account , not expected come during normal operations. different languages have different rules exceptional, happens 16% of time not exceptional, unusual.

exceptions expensive because involve stack unwind , jump, pausing of normal processing, , search handler. if/then standard, normal conditional efficient , clear.


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -