Re: A technique from a chatbot

Liste des GroupesRevenir à cl python 
Sujet : Re: A technique from a chatbot
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.python
Date : 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 = }' )

Date Sujet#  Auteur
2 Apr 24 * A technique from a chatbot15Stefan Ram
2 Apr 24 +* Re: A technique from a chatbot12Piergiorgio Sartor
2 Apr 24 i+* Re: A technique from a chatbot8Thomas Passin
4 Apr 24 ii`* Re: A technique from a chatbot7Mark Bourne
4 Apr 24 ii +* Re: A technique from a chatbot2<avi.e.gross
5 Apr 24 ii i`- Re: A technique from a chatbot1Mark Bourne
4 Apr 24 ii +- Re: A technique from a chatbot1Thomas Passin
5 Apr 24 ii `* Re: A technique from a chatbot3Stefan Ram
5 Apr 24 ii  +- Re: A technique from a chatbot1Stefan Ram
5 Apr 24 ii  `- Re: A technique from a chatbot1Mark Bourne
3 Apr 24 i+- Re: A technique from a chatbot1<avi.e.gross
3 Apr 24 i+- Re: A technique from a chatbot1Thomas Passin
3 Apr 24 i`- Re: A technique from a chatbot1<avi.e.gross
3 Apr 24 +- Re: A technique from a chatbot1Pieter van Oostrum
3 Apr 24 `- Re: A technique from a chatbot1Michael F. Stemper

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal