Sujet : Re: A technique from a chatbot
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.pythonDate : 05. Apr 2024, 20:32:22
Autres entêtes
Organisation : Stefan Ram
Message-ID : <return-20240405193045@ram.dialup.fu-berlin.de>
References : 1 2 3 4 5 6
ram@zedat.fu-berlin.de (Stefan Ram) wrote or quoted:
However, I also tested code with an early return (not shown below),
and this was shown to be faster than both code using break and
code using next+generator by a factor of about 1.6, even though
the code with return has the "function call overhead"!
See "return" benchmarked against "break" below!
import random
import string
import timeit
print( 'The following loop may need a few seconds or minutes, '
'so please bear with me.' )
def get_word_using_return( list_ ):
for word in list_:
if word[ 0 ]== 'e':
return word
return ''
time_using_break = 0
time_using_return = 0
for repetition in range( 100 ):
for i in range( 100 ): # Yes, this nesting is redundant!
list_ = \
[ ''.join \
( random.choices \
( string.ascii_lowercase, k=random.randint( 1, 30 )))
for i in range( random.randint( 0, 50 ))]
start_time = timeit.default_timer()
for word in list_:
if word[ 0 ]== 'e':
word_using_break = word
break
else:
word_using_break = ''
time_using_break += timeit.default_timer() - start_time
start_time = timeit.default_timer()
word_using_return = get_word_using_return( list_ )
time_using_return += timeit.default_timer() - start_time
if word_using_return != word_using_break:
raise Exception( 'word_using_return != word_using_break' )
print( f'{time_using_break = }' )
print( f'{time_using_return = }' )
print( f'{time_using_return / time_using_break = }' )