Python is amazing, except for it is a bit slow compared to other languages like C, C++, and Java. On online coding platforms if for C/C++ time provided is X, then Python will be 5X while doing same data science functions.
For improving the speed of code execution, we have various input and output procedures.
Suppose we have to find the sum of N numbers. Firs we will input the value of N and then we will write N numbers separate by single space in a line.
Python solutions for the above problem:
Normal Method Python (Python 2.7):
- raw_input(): It will take an optional prompt argument. It will also strip the trailing new line character from the string when it is return.
- print: It is a thin wrapper that formats the inputs and calls the write function of an object.
A faster method by using in-built stdin, stdout (Python 2.7):
- stdin: It is a file object. It is the creation of another file object which could be create for reading input from the file. The file will be a standard input buffer in this case.
- write(‘D\n’): It is much faster than the print ‘D’ function.
- write(“”.join(list-comprehension)): It is an even faster method but in this memory usage is dependent on the size of the input.
The difference in time is below:
Addition of buffered pipe io (Python 2.7):
- The output can be made faster simply by adding the buffered IO code before the submission code.
- The main benefit of BytesIO is that it implements a common-ish interface (commonly called file like object). BytesIO objects consists of an internal pointer, and for every call to read(n) the pointer will advance.
- The module atexit provides a simple interface for registration of functions to be called when program closes normally. Even the sys module provides a hook, sys.exitfunc but the problem is we can only register one function here. We can use the atexit registry for multiple modules and libraries simultaneously.
Note: We need to simply replace the raw_input() with input() syntax of Python 3.X for using the above codes in Python 3.X.