I've been using sys.stdin
to avoid ʻinput ()` somehow, but which one is better? I compared the speed and the amount of code. In addition, fileinput is also compared.
The operating speed is input() >>> fileinput > sys.stdin
--Use the online execution environment paiza.io (no particular meaning).
--Pass a number + blank format such as 1 2 3 4
** 10,000 lines ** as standard input.
--Use time
to measure the time it takes to convert standard input to int and store it in list.
input()Code example.py
data_all = [input().split() for i in range(10000)]#Collective data acquisition
data_list = [[int(s) for s in line]for line in data_all] #Data int
#for line in data_all:
# data_list.append([int(s) for s in line])
Operating time: Approximately 21.1 [msec]
sys code example.py
data_list = [ [int(s) for s in line.split()] for line in sys.stdin ]
#data_list = []
#for line in sys.stdin:
# data_list.append([int(s) for s in line.split()])
Operating time: Approximately 10.5 [msec]
import fileinput
data_list = [ [int(s) for s in line.split()] for line in fileinput.input() ]
Operating time: Approximately 12.5 [msec]
I changed it to a comprehension notation. If I use input (), it will be 2 lines ...
The operation speed of input () is almost twice as slow. Looking at other people's articles, it seems that there is a difference of 10 times or more. It seems better to use sys
.
I tried additional fileinput, but it wasn't as fast as sys.stdin.
In the case of input (), about 12.9 [msec] For sys.stdin, about 5.5 [msec] For fileinput, about 7.5 [msec] Int conversion takes a surprising amount of time. After all sys.stdin seems to be faster in operation speed.
Recommended Posts