Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if my code is running through Cython or standard Python interpreter?

Tags:

python

cython

is there a reliable way to check at runtime if some python code is "cythonized" or if it us running into a standard Python interpreter ? Thanks !

like image 417
user3274434 Avatar asked Mar 20 '15 15:03

user3274434


2 Answers

Answering this because this question comes up as a top response on search engines and the answers aren't helpful.

From http://docs.cython.org/en/latest/src/tutorial/pure.html

import cython
if cython.compiled:
    print("Yep, I'm compiled.")
else:
    print("Just a lowly interpreted script.")
like image 140
MB. Avatar answered Nov 01 '22 20:11

MB.


When I import similar modules and look at their .__file__ attributes I get

In [205]: which.__file__
Out[205]: .../which.py'

In [206]: which_cy.__file__
Out[206]: '.../which_cy.cpython-34m.so'

The cythonized module is imported from a .so file, while the python source is .py (or .pyc). But there are other ways of compiling code which will also create .so files. So this doesn't distinguish among compilation routes.

And for individual functions:

In [225]: repr(which.nonzero)
Out[225]: '<function nonzero at 0xb4dd2d1c>'

In [226]: repr(which_cy.nonzero_cy)
Out[226]: '<built-in function nonzero_cy>'

cython does not 'run' code. It translates a file (e.g. *.pyx) into C code. That is then compiled, producing a loadable module (the .so) file. That is then imported and run by the Python interpreter. I don't know if there's a way of running the .so code as a stand along executable.

Or, are you really wondering whether the code in a given compiled module is using tight C code as opposed to calls to Python functions (mainly Python objects and their methods)? You can look at the C code for that. Both are using compiled code, but one has a lot of overhead from checking types, bounds, etc. The whole point to Cython tutorials is ways to shift away the Python generality to faster C definitions.

like image 5
hpaulj Avatar answered Nov 01 '22 20:11

hpaulj