Forum Archive

print is slow

wolf71

Pythonista using print function is very slow.

can using other method to improve speed?

ccc

Where possible, try to call print() as few times as possible by bundling up a bunch of lines of text into just one call to print().

Like:

my_text = '''Triple quoted strings
 allow you to
 create
 strings
 that are
 multiple
 lines long.'''

print(my_text)
# is faster than
for line in my_text.splitlines():
    print(line)

# or use str.join()
import string
print('\n'.join([c for c in string.lowercase]))
# is faster than
for c in string.lowercase:
    print(c)
wolf71

thanks @ccc

s=''
for i in range(100):
s += 'test afsdafdsaf\n'
print s

it's fast,but sometime I need print split. etc: output process info.

can speed up every time print output ?

ccc

Is the text that you a printing out for your end user or is it just for you own debugging purposes? If the latter, consider using logging instead of printing.

It is also possible to redirect stdout to a file instead of the console which will be much faster but I find that complex/counterintuitive.

You could also create a ui.TextView and write your text there: text_view.text += 'new message'