Introduction
In Python, the input() function is convenient to use, but it is very slow when called repeatedly.
For problems like Baekjoon 15552 that require reading input more than 100,000 times, using input()
can lead to a time limit exceeded error. Using sys.stdin.readline(), the same task can
be handled tens of times faster. I/O optimization is independent of the algorithm itself, but
it is a crucial skill in competitive programming to save time using Pass/Fail.
Learning Objectives
- Be able to explain why
sys.stdin.readline()is faster thaninput(). - Be able to write code that handles various input patterns (single values, space-separated, multiple lines, EOF).
- Be able to apply output optimization techniques (
sys.stdout.write,'\\n'.join()).
Key Concepts
1. input() vs sys.stdin.readline() speed comparison
| Method | Internal operation | Time to process 100,000 lines (approx.) | Features |
|---|---|---|---|
input() |
Flushes every time, includes prompt handling | Convenient but slow | |
sys.stdin.readline() |
Reads directly from buffer | Fast but includes \n |
|
sys.stdin.read() |
Reads everything at once | Fastest, parsing required |
Key point:
input()triggers a system call every time, whereassys.stdin.readline()utilizes an internal buffer.
2. Caution with sys.stdin.readline(): newline character (\n)
import sys
line = sys.stdin.readline() #'42\n' ← Includes \n at the end!
line = sys.stdin.readline().strip() #'42' ← Correct usage
n = int(sys.stdin.readline()) #When converting with int(), \n is automatically ignored
Most common mistake: Forgetting .strip() when receiving as a string, causing comparison errors.
3. Frequently used input patterns
import sys
input = sys.stdin.readline #Overwriting input() (most common pattern)
#A single integer
n = int(input())
#Two integers separated by space
a, b = map(int, input().split())
#A line of integer list
arr = list(map(int, input().split()))
#n lines of input
lines = [input().strip() for _ in range(n)]
#Read all at once (for large input)
data = sys.stdin.read().split() #List of tokens separated by space/newline
4. sys.stdout.write vs print()
| Method | Time to print 100,000 lines | Features |
|---|---|---|
print() |
Convenient, auto newline, slow | |
sys.stdout.write() |
Fast, need to add \n manually |
|
'\n'.join() + single output |
Fastest, collect in a list and output |
import sys
#Slow method — repeated calls to print()
for x in results:
print(x)
#Fast method — print all at once
sys.stdout.write('\n'.join(map(str, results)) + '\n')
#Or
print('\n'.join(map(str, results)))
5. EOF (End of File) handling
When the number of input lines is unknown and you need to read until the end of the file:
import sys
#Method 1: try/except (safest)
try:
while True:
line = input() #Or sys.stdin.readline().strip()
if not line:
continue
#Processing...
except EOFError:
pass
#Method 2: for line in sys.stdin (Pythonic)
for line in sys.stdin:
line = line.strip()
if not line:
continue
#Processing...
#Method 3: read all and then parse
data = sys.stdin.read().split()
Examples
Example 1: speed comparison of input() vs readline() (src/01_input_comparison.py)
Measure the speed of both methods directly using mock data.
python src/01_input_comparison.py
[Expected Output]
input() Simulation : 0.4523 seconds
sys.stdin.readline() Simulation: 0.0321 seconds
sys.stdin.read().split(): 0.0089 seconds
Example 2: competitive programming I/O template (src/02_fast_io_template.py)
Summarize I/O patterns that can be used directly in practice.
python src/02_fast_io_template.py
Example 3: output optimization (src/03_output_optimization.py)
Compare print() vs sys.stdout.write() vs buffered output.
python src/03_output_optimization.py
Example 4: EOF handling (src/04_eof_handling.py)
Show various patterns for reading until EOF.
python src/04_eof_handling.py
Common Mistakes
-
Not removing
\nfromsys.stdin.readline()#Incorrect code s = sys.stdin.readline() # '42\n' if s == '42': # False! '42\n' != '42' ... #Correct code s = sys.stdin.readline().strip() # '42' -
Overwriting
input = sys.stdin.readlineand missing.strip()input = sys.stdin.readline n = int(input()) #OK — ignore \n when converting with int() s = input().strip() #OK — strings must be stripped() s = input() #Danger — string contains \n -
Printing the output line by line with print() — TLE when there are many prints
- For Baekjoon problem 15552, you need to optimize not only input but also output.
- Print at once using
'\n'.join(map(str, results)).
-
Index error after sys.stdin.read().split()
data = sys.stdin.read().split() #You need to parse in the order of data[0], data[1], ... #Be careful of mistakes in index calculation! -
Infinite loop without EOF
#Incorrect code — infinite loop when stdin is a pipe while True: line = sys.stdin.readline() #If line is an empty string (''), it is EOF if not line: #Without this check, it will be an infinite loop! break
Summary
| Situation | Recommended Method |
|---|---|
| When there are many input lines | sys.stdin.readline() or sys.stdin.read() |
| Simple 1–2 line input | Using input() is fine |
| When there are many output lines | '\n'.join(map(str, results)) + single print |
| When you need to read until EOF | for line in sys.stdin |
Try it yourself
- Run
src/01_input_comparison.pyand check the actual speed difference. - Write
boj_15552.pyand submit it to Baekjoon. - Find code you've written before where
input()is used a lot and try improving it withsys.stdin.readline().