Python Forum
print a list strings is fast but printing the joined strings is slow
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
print a list strings is fast but printing the joined strings is slow
#7
(Aug-26-2019, 09:03 AM)Malt Wrote: here it is displaying timer after printing okay for 4 times.
You don't need loop with timeit is doing loop in number=4 .
It run the code 4 times and give average time back.
Be using print() as mention you get different result back.
This is not how fast the code run,but the printing to screen in interactive shell in this case.

Here a more realistic example there where a discussion a while back about which was faster,word[0] or startswith().
See that i don't use print() here i want to measure code speed,and not the printing to screen.
import timeit

def time_1(word):
    if word[0] in ('w','x','y','z'):
        f'word <{word}> has a first letter in sequence <wxyz>'

def time_2(word):
    if word[0] in 'wxyz':
        f'word <{word}> has a first letter in sequence <wxyz>'

def time_3(word):
    if word.startswith(('w','x','y','z')):
        f'word <{word}> has a first letter in sequence <wxyz>'

lst = ['time_1', 'time_2', 'time_3']
for test in lst:
    t = timeit.Timer(f"{test}('war'*5)", f'from __main__ import {test}').timeit(number=10000000)
    print(f'{test} --> {t:.2f}')
So this run each code in function 10000000 times,and we get average time back.
Output:
E:\div_code λ python time_startswith.py time_1 --> 3.49 time_2 --> 3.53 time_3 --> 5.01
So word[0] is a little faster than startswith().
Dos this mean that should use word[0]?
My answer was no because startswith() is more readable and the time differences is really small.
Reply


Messages In This Thread
RE: print a list strings is fast but printing the joined strings is slow - by snippsat - Aug-26-2019, 10:49 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Mapped Strings edualfaia 12 2,381 Sep-04-2023, 11:08 AM
Last Post: snippsat
Question bytes and strings Skaperen 0 831 Aug-28-2023, 02:58 AM
Last Post: Skaperen
  f-strings round float down too much Skaperen 5 2,714 Dec-29-2021, 08:37 PM
Last Post: Skaperen
  f-strings in a script to be made public Skaperen 2 2,219 Jan-03-2020, 06:03 PM
Last Post: Skaperen
  supporting both strings and bytes in functions Skaperen 0 1,480 Nov-28-2019, 03:17 PM
Last Post: Skaperen
  side effects in f-strings Skaperen 0 1,726 Sep-08-2019, 01:26 AM
Last Post: Skaperen
  trying to learn f-strings - puzzled by format() protocol Skaperen 7 3,860 Jul-26-2019, 08:40 PM
Last Post: Skaperen
  mixing bytes with strings Skaperen 3 2,514 May-29-2019, 02:30 AM
Last Post: heiner55
  to strings or to bytes, that is the question Skaperen 0 2,100 Jul-07-2018, 08:35 PM
Last Post: Skaperen
  mutable strings Skaperen 3 3,623 Dec-03-2017, 03:05 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020