Macaulay2's language is interpreted, which means that in general programs will run more slowly than programs written in a compiled language like C. If the speed of a compiled language is desirable, then one option is just-in-time compilation (JIT), where we compile some code at runtime.
As an example, let's suppose that we would like to compute Fibonacci numbers using the recursive definition, i.e., for all nonnegative $n\in\ZZ$, $F_n = n$ if $n < 2$ and $F_n = F_{n-2} + F_{n-1}$ otherwise. As an algorithm, this is horribly inefficient and has exponential running time, but it will be useful to illustrate our point.
We will write two functions. One will be a straight Macaulay2 implementation:
|
The next will be a function that creates a C source file, compiles it into a shared library using GCC, opens that library using openSharedLibrary, calls foreignFunction to create a foreign function, calls that foreign function, and then converts the output back into a Macaulay2 integer using value(ForeignObject).
|
Now let's run both functions to compare the results.
|
|
As we can see, despite the additional overhead of creating a shared library and making a foreign function call, the function that used JIT was significantly faster.
The source of this document is in /build/reproducible-path/macaulay2-1.25.05+ds/M2/Macaulay2/packages/ForeignFunctions.m2:2378:0.