Back: Programming
Previous: Iterating with Nest and Fold
Next: MathLink
Programming in Mathematica
Compiling functions, and timing
If a function is intended to give a numerical value rather than a
symbolic value, it can be compiled to take advantage of a computer's
arithmetic hardware, and will often return numerical values must more
quickly than its uncompiled counterpart. Here we use Timing to compare
the speed of compiled and uncompiled versions of a simple function:
Remove[f,cf];
f = Function[{x,y}, Sin[x]/(Abs[y]+1.7)];
cf = Compile[{x,y}, Sin[x]/(Abs[y]+1.7)];
{f[3,7], cf[3,7]}
{0.114943 Sin[3], 0.0162207}
Time how long it takes (approx) to do 1000 calculations with each version:
Timing[ Do[ f[3,7], {1000}];"-- uncompiled" ]
Timing[ Do[cf[3,7], {1000}];"-- compiled" ]
{0.416667 Second, -- uncompiled}
{0.0666667 Second, -- compiled}