The document discusses different methods for optimizing Python code for plotting the bifurcation diagram of the logistic map, including PyPy, C extensions, and Cython. PyPy can speed up Python code without changes but does not support matplotlib. C extensions can provide large speedups but require writing C code. Cython allows generating C code from Python-like code and provides speed gains with less effort than C extensions. The document demonstrates using Cython to optimize the logistic map bifurcation diagram code.
11. That was a little disappointing
Nothorrible, buttoo slow to do some coolstuff.
12. Options for doing better
0. Quitusingpython
1. PyPy
2. C extension
3. Cython
4. There are others (numpywith numexpr)
13. PyPy
Straightfrom pypy.org:
Fast, compliantalternative implementation of the Python
language (2.7.6 and 3.2.3) with severaladvantages:
Speed, due to Just-In-Time compiler
Takes less memory
Supports anumber of third partylibraries:
ctypes, django, sqlalchemy, twisted, etc.
Does notrequire anychange to your code!
Unfortunately, matplotlib is notsupported.
Numpyis partiallysupported.
14. C extensions
Write functions in C thatare callable from python
Pass python objects as arguments thatmustbe converted to C
values
Returns apython object, e.g., alist
Compiled and fast
Do this atleastonce
16. Compiling to an importable module
Create asetup.pyfile, e.g:
fromdistutils.coreimportsetup,Extension
setup(name='logmap',version='1.0',
ext_modules=[Extension('logmap',['logmapmodule.c'])])
Then installit
>>>pythonsetup.pyinstall
And itcan be imported and called
importlogmap
h= logmap.attractor_histogram(...)
18. Cython
Directlyfrom cython.org:
Static compiler for python
Makes writingC extensions for python as easyas writing
python
Generates C code from your python code
Has the potentialto deliver the speed gains thatwe getfrom aC
extension with less hassle
19. How to make it work
Create setup.pyfile:
Build like this:
Then you can importfrom
logistic_map_bifurcation_diagram_cython
fromdistutils.coreimportsetup
fromCython.Buildimportcythonize
setup(
name='logmap_cython',
ext_modules=cythonize("logistic_map_bifurcation_diagram_cython.pyx"),
)
%>pythonsetup.pybuild_ext--in_place
20. Making cython faster
Cython's code generation is helped byprovidingithints in the
form of type declarations
deflogmap_histogram(floatr1,floatr2,intrrlen,intxxlen,floatx1,floatx2,intM)
result=[0]*M
cdeffloatdx
dx=1.0*(x2-x1)/(M-1)
transient=500
cdeffloatx
cdeffloatr
cdeffloatk
forrinlinspace(r1,r2,rrlen):
x=0.25
forkinrange(transient):
x=x*r*(1-x)
forkinrange(xxlen):
x=x*r*(1-x)
incr=int((x-x1)/dx)
ifincr>=0andincr<M:
result[incr]+=1
returnresult