[plt-scheme] Fractals

From: Eli Barzilay (eli at barzilay.org)
Date: Wed Sep 20 17:54:02 EDT 2006

On Sep 20, Joshua Zucker wrote:
> I've done some profiling so I know exactly where my code spends most
> of its time (divided almost equally among the innermost loops of
> several floating point calculations).

You can easily rewrite these parts in C (or anything else that
compiles to a standard .so/.dll).  Here's a quick demonstration -- say
that I want a floating point Fibonacci function, I write this code:

  double fib(double n) {
    if (n <= 1.0) return n;
    else return fib(n-1.0) + fib(n-2.0);

On Linux, I compile & link it with:

  gcc -c fib.c && ld -shared fib.o -o fib.so

Then I use it in Scheme as follows:

  > (require (lib "foreign.ss"))
  > (unsafe!)
  > (define fib (get-ffi-obj "fib" "./x.so" (_fun _double -> _double)))
  > (fib 10.0)

Note that _double works only with floating point numbers:

  > (fib 10)
  Scheme->C: expects argument of type <double>; given 10

and there is a _double* that will coerce the input to a FP number:

  > (define fib (get-ffi-obj "fib" "./x.so" (_fun _double* -> _double)))
  > (fib 10)

As for using loops -- every time a floating point number passes from
the C side to Scheme, it gets allocated -- so you probably want to do
the loops in C too.  (The amount of C code that you'd want to use that
keeps a balance of good maintainable code and efficiency is something
that you'll need to experiment with...)

> of course there are also ways (by rearranging my data structures,
> and using better computational geometry algorithms than the naive
> ones I've implemented so far, and so on) that I can get a speedup of
> a factor of a few by doing some more work programming in PLT Scheme.

(Migrating code to C will buy you linear speedup -- improving the
algorithm is always a better idea, and I'd start with that before
touching C.)

          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                  http://www.barzilay.org/                 Maze is Life!

Posted on the users mailing list.