====== Output in Python3 ====== There is no magic bullet that leads to the fastest input and output in a programming contest. Having said this, there are typically multiple ways of performing and processing input and output in Python3. By understanding the options that are available and how to optimize them (e.g., conducting tests) you can see a real world performance increase, in particular when faced with high volumes of reads and writes. Unlike [[python3:input|Python3 input]], we noted less dramatic changes when the faster ''stdout.write()'' call was used over ''print()''.((It is possible that ''print()'''s implementation is a thin wrapper around something like ''stdout.write()'', in which case the formatting and convenience of ''print()'' account for the major differences.)) In instances where you believe very small fractions of a second may get you out of a //time limit exceeded// judgement, switching may be warranted (in particular when the number of writes are excessive). Otherwise, fine tuning of algorithm implementations and input or the selection of C++ may be better choices than fine tuning ''print()''. ===== Output Basics ===== Output is handled with the ''%%print()%%'' function. >>> print() # '\n' >>> print("Hello World!") # "Hello World!\n" >>> print("Hello", "World!") # "Hello World!\n" >>> print(1, 2, 3, sep='') # "123\n" >>> print(1, 2, 3, end='-') >>> print("a b c") # "1 2 3-a b c\n" ===== Advanced Output ===== >>> from sys import * >>> stdout.write('\n') 1 ''stdout.write()'' returns the number of characters written to the underlying stream, but only prints the information in the context of the [[competitive_programming:python_interpreter|interactive interpreter]].((This information is suppressed when ''stdout.write()'' is used in the context of a ''.py'' file, and hence requires no special handling in contests.)) >>> from sys import * >>> stdout.write("Hello World!\n") # "Hello World!\n" Hello World! 13 Unlike ''print()'', ''stdout.write()'' takes only a single parameter and offers no formatting options. ''stdout.write()'' over multiple strings requires multiple calls or concatenations. Other types must be converted to string before they are printable. ==== Benchmarks ==== The following benchmarks demonstrate the increased likelihood of failure of ''print()'' as output sizes increase. All files used for testing can be found [[files:python3:output_tests|here]]. 10 characters per line (//n//= number of lines): | //n// | print() | sys.stdout.write() | | 104 | .006 | .002 | | 105 | .059 | .022 | | 106 | .378 | .202 | 1000 characters per line (//n//= number of lines): | //n// | print() | sys.stdout.write() | | 104 | .016 | .011 | | 105 | 3.886 | 3.652 | The above tests were designed to showcase minimal printing functionality on data that is currently residing in memory.