3

First of all, I know the difference between py and pyc files. I also understand that running time of both the files will be the same.

But I have a doubt here. pyc removes the loading time associated with a python execution. Is there way I can perceive this? When I run a normal py file it takes x secs to load and y secs to run. A pyc file would also take y secs to run. Is there a way by which I can measure the x secs difference between the two?

codingsplash
  • 4,785
  • 12
  • 51
  • 90
  • What exactly do you want to calculate. Time take to convert a py file to pyc? If that's the case then use [`py_compile.compile`](https://docs.python.org/2/library/py_compile.html#py_compile.compile) and write to different temporary files and `timeit`. Or basic `%timeit py_compile.compile('your_file.py')` will also do considering [it creates](https://hg.python.org/cpython/file/2.7/Lib/py_compile.py#l71) a new pyc file each time. (Note: `%timeit` is for IPython shell, in normal shell use the `timeit` module) – Ashwini Chaudhary Nov 09 '15 at 05:21

1 Answers1

1

Python .py files are compiled into .pyc files. .pyc files are the files, which python interpreter can understand and execute. Thus, You must be clear that compilation and loading is different. Compilation means converting .py text-formatted source file into .pyc binary formatted bytecodes. Loading means analyzing and instantiating the symbols and source-code(in binary form) present in .pyc file into memory, so that program execution can continue.

Coming to your question, there're several ways to measure this :-

Create two module files module1.py and module2.py. In module2.py, import module1.py. Use timeit python module in module2.py to find the load time of module1.py. For info. on how to use timeit module, refer How to use timeit module.

Run module2.py from command prompt, in two cases :- (1) when .pyc file for module1 is present, (2) when .pyc file for module1 is not present.

By the way, you may or may not notice any significant difference in timings in both cases. However it depends how much lines of code and imports are done in module1.py

Hoping it'll helps you.

Community
  • 1
  • 1
Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97
  • The difference of timing should not be dependent on the numbers of import done on `module1.py`. By the way to be clearer you could rename `module1` to `imported_module` and `module2` to `main_module` – Xavier Combelle Nov 09 '15 at 10:35
  • Here's an excellent explainig in which way pyc files increase performance: http://effbot.org/pyfaq/can-python-be-compiled-to-machine-code-c-or-some-other-language.htm – Jean-Pierre Schnyder Mar 03 '17 at 09:27