5.2 Creating Compiled Code

Speed is crucial in mathematical computations. Though Python is a convenient very high-level language, certain calculations can be several orders of magnitude faster than in Python if they are implemented using static types in a compiled language. Some aspects of Sage would have been too slow if it had been written entirely in Python. To deal with this, Sage supports a compiled ``version'' of Python called Cython ([Cyt] and [Pyr]). Cython is simultaneously similar to both Python and C. Most Python constructions, including list comprehensions, conditional expressions, code like += are allowed; you can also import code that you have written in other Python modules. Moreover, you can declare arbitrary C variables, and arbitrary C library calls can be made directly. The resulting code is converted to C and compiled using a C compiler.

In order to make your own compiled Sage code, give the file an .spyx extension (instead of .sage). If you are working with the command-line interface, you can attach and load compiled code exactly like with interpreted code (at the moment, attaching and loading Cython code is not supported with the notebook interface). The actual compilation is done ``behind the scenes'' without your having to do anything explicit. See SAGE_ROOT/examples/programming/sagex/factorial.spyx for an example of a compiled implementation of the factorial function that directly uses the GMP C library. To try this out for yourself, cd to SAGE_ROOT/examples/programming/sagex/, then do the following:

sage: load "factorial.spyx"
***************************************************
                Recompiling factorial.spyx
***************************************************
sage: factorial(50)
30414093201713378043612608166064768844377641568960512000000000000L
sage: time n = factorial(10000)
CPU times: user 0.03 s, sys: 0.00 s, total: 0.03 s
Wall time: 0.03
Here the trailing L indicates a Python long integer (see 7.1.2).

Note that Sage will recompile factorial.spyx if you quit and restart Sage. The compiled shared object library is stored under $HOME/.sage/temp/hostname/pid/spyx. These files are deleted when you exit Sage.

NO Sage preparsing is applied to spyx files, e.g., 1/3 will result in 0 in a spyx file instead of the rational number $ 1/3$ . If foo is a function in the Sage library, to use it from a spyx file import sage.all and use sage.all.foo.

import sage.all
def foo(n):
    return sage.all.factorial(n)



Subsections
See About this document... for information on suggesting changes.