I am quoting a part of Python documentation:
“A program doesn’t run any faster when it is read from a .pyc or .pyo file than when it is read from a .py file; the only thing that’s faster about .pyc or .pyo files is the speed with which they are loaded.”
I don’t understand what does it mean when it says it doesn’t affect the running time but the loading time? Could someone please explain it a little deep that I can understand completely?
There are two steps in converting the Python code you write to instructions the computer can understand:
A compile step. The raw Python code is converted to Python bytecode. This bytecode will be recognised by a Python interpreter on any operating system, on any hardware. This is what is stored in a .pyo or .pyc file.
An interpretation step. The Python interpreter, or if you prefer the Python virtual machine, interprets the bytecode and sends low-level instructions to the computer. These low level instructions will be different between Linux and Windows, or between an Intel chip and an AMD, etc, so someone has to write a different interpreter for each type of system that Python can be run on.
When you run code from a .pyc file, step 1 has already been completed, so the execution goes straight to step 2. But step 2 runs just as fast as it would run if you compiled it immediately before running it. Whether the compile step slows down your code significantly depends on what your program does. You should experiment to see how big a difference waiting for your code to compile takes, but if you are writing short scripts the difference will probably be unnoticeable.