This is an old revision of the document!
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.
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"
print()
is a wrapper around Python's write()
. In some instances, write()
may outperform print()
.
write()
requires a single str
argument. write()
does not perform concatenation, and does not automatically insert a \n
at the end of your output. write()
returns the number of characters written to the underlying stream. This is hidden in competition environments, but it will appear if testing in the interactive interpreter.
>>> from sys import * >>> stdout.write('\n') # '\n'
>>> from sys import * >>> stdout.write("Hello World!\n") # "Hello World!\n"
Concatenation is possible, but needs to be done with the +
operator.
>>> from sys import * >>> stdout.write("Hello" + " " + "World!" + "\n") # "Hello World!\n"
Numbers can be written using write()
, but they need to be cast to string (str()
) and then concatenated with +
.
>>> from sys import * >>> x = 12 >>> stdout.write("x is: " + str(x) + "\n") # "x is: 12\n"
The following benchmarks demonstrate the increased likelihood of failure of print()
as output sizes increase. All files used for testing can be found 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.