python - sys.stdin.readline() and input(): which one is faster when reading lines of input, and why? -


i'm trying decide 1 use when need acquire lines of input stdin, wonder how need choose them in different situations.

i found previous post (https://codereview.stackexchange.com/questions/23981/how-to-optimize-this-simple-python-program) saying that:

how can optimize code in terms of time , memory used? note i'm using different function read input, sys.stdin.readline() fastest 1 when reading strings , input() when reading integers.

is statement true ?

the builtin input , sys.stdin.readline functions don't same thing, , 1 faster may depend on details of you're doing. aruisdante commented, difference less in python 3 in python 2, when quote provide from, there still differences.

the first difference input has optional prompt parameter displayed if interpreter running interactively. leads overhead, if prompt empty (the default). on other hand, may faster doing print before each readline call, if want prompt.

the next difference input strips off newline end of input. if you're going strip anyway, may faster let input you, rather doing sys.stdin.readline().strip().

a final difference how end of input indicated. input raise eoferror when call if there no more input (stdin has been closed on other end). sys.stdin.readline on other hand return empty string @ eof, need know check for.

there's third option, using file iteration protocol on sys.stdin. calling readline, perhaps nicer logic it.

i suspect while differences in performance between various options may exist, they're liky smaller time cost of reading file disk (if large) , doing whatever doing it. suggest avoid trap of premature optimization , natural problem, , if program slow (where "too slow" subjective), profiling see taking time. don't put whole lot of effort deciding between different ways of taking input unless matters.


Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -