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. It is virtually impossible to write serious competitive computer algebra software if one restricts oneself to interpreted Python code.
To deal with this problem, 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, one 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). You can attach and
load compiled code exactly like with interpreted code. The actual
compilation is done ``behind the scenes'' without your having to do
anything explicit. See SAGE_ROOT/examples/pyrex/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/pyrex/, 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
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
. 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)