Fast I/O for Competitive Programming in Python
Last Updated :
03 Nov, 2020
In Competitive Programming, it is important to read input as fast as possible to save valuable time. Input/Output in Python can be sometimes time taking in cases when the input is huge or to output any numbers of lines or a huge number of arrays(lists) line after line.
Fast Input
Normally, the input is taken from STDIN in the form of String using input(). And this STDIN is provided in the Judge’s file. So try reading the input directly from the Judge’s file using the Operating system(os) module, and input/output (io) module. This reading can be done in the form of bytes. By using this method, integer input works normally, but for string input, it will store the string as a byte like an object. For correcting this, the string can be decoded using the decode function.
Below is the implementation for Fast I/O in Python:
Python3
import io, os, time
def normal_io():
start = time.perf_counter()
s = input ().strip();
end = time.perf_counter()
print ( "\nTime taken in Normal I / O:" , \
end - start)
def fast_io():
input = io.BytesIO(os.read( 0 , \
os.fstat( 0 ).st_size)).readline
start = time.perf_counter()
s = input ().decode()
end = time.perf_counter()
print ( "\nTime taken in Fast I / O:" , \
end - start)
if __name__ = = "__main__" :
normal_io()
fast_io()
|
Output:
Fast Output
Instead of outputting to the STDOUT, we can try writing to the Judge’s system file. The code for that would be to use sys.stdout.write() instead of print() in Python. But remember we can only output strings using this, so convert the output to a string using str() or map().
Below is the implementation for the Fast Output:
Python3
import time, sys
def normal_out():
start = time.perf_counter()
n = 5
print (n)
s = "GeeksforGeeks"
print (s)
arr = [ 1 , 2 , 3 , 4 ]
print ( * arr)
end = time.perf_counter()
print ( "\nTime taken in Normal Output:" , \
end - start)
def fast_out():
start = time.perf_counter()
n = 5
sys.stdout.write( str (n) + "\n" )
s = "GeeksforGeeks\n"
sys.stdout.write(s)
arr = [ 1 , 2 , 3 , 4 ]
sys.stdout.write(
" " .join( map ( str , arr)) + "\n"
)
end = time.perf_counter()
print ( "\nTime taken in Fast Output:" , \
end - start)
if __name__ = = "__main__" :
normal_out()
fast_out()
|
Output:
Please Login to comment...