Hi Pythonistas!
Today we are going the check the performance difference between print and sys.stdout.write in Python. We know that both are for output text to standard output. Let us check this with code
Code
import timeit
import sys
def print_hello():
print("print hello")
def stdout_hello():
sys.stdout.write("stdout hello")
time_for_print = timeit.timeit(print_hello, number=1000_000)
time_for_stdout = timeit.timeit(stdout_hello, number=1000_000)
print("Time for print: ", time_for_print)
print("Time for stdout: ", time_for_stdout)
Output
Time for print: 2.661877478000065
Time for stdout: 0.5633935490000113
sys.stdout.write is much faster that print.
Why
Becase stdout.write only write to stdout. It can write only string to stdout. If we pass any other datatype this will raise an error
Eg
>>> import sys
>>> sys.stdout.write(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: write() argument must be str, not int
>>> sys.stdout.write([1, 2, 3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: write() argument must be str, not list
>>> sys.stdout.write({"a": 1})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: write() argument must be str, not dict
Inorder todo print this first we need to convert to string then pass to the function. But print can print any data type, because this function automatically convert non string datatypes to string before writing to the stdout. Also print add new line at the ending by default. This conversion and formatting takes the extra time
Hope you have learned something from this post please share your suggestions with afsal@parseltongue.co.in