[racket] Perlin and simplex noise - optimizing Racket code

From: Vincent St-Amour (stamourv at ccs.neu.edu)
Date: Fri Apr 12 11:32:42 EDT 2013

At Thu, 11 Apr 2013 22:06:30 -0400,
JP Verkamp wrote:
> Real will work? (Well, considering you did it I'd assume so.) For whatever
> reason, I assumed that I would have to use Flonum to get the floating point
> optimizations, but that leads to the issues I had with 0 not typechecking
> from the other email.

`Real' will typecheck, but it won't be optimized. As you said, only
`Float' types allow floating-point specializations.

> In any case, I actually ran it. In practice, Real has essentially the same
> performance as Flonum without the annoying issue with 0, so that's good. So
> then when would you specifically want to use Flonum instead of Real?

It may be that these operations were in cold code, so the specialization
did not have much impact.

The most recent version of Optimization Coach (available in the package
repository, and requires a pre-release Racket) can use profiling
information to refine its recommendations. If the operations you mention
were in cold code, the new version would not consider them worth telling
you about.

> After the Float/Real/Flonum changes, I ended up writing this code:
> 
> (: perlin (case-> (Real -> Real)
>                   (Real Real -> Real)
>                   (Real Real Real -> Real)))
> (define (perlin x [y 0.0] [z 0.0])
>   (perlin^ (real->double-flonum x)
>            (real->double-flonum y)
>            (real->double-flonum z)))
> 
> (: perlin^ (Float Float Float -> Float))
> (define (perlin^ x y z)
>   ...)
> 
> *Are there any obvious pitfalls I'm missing with this approach?*

I don't see any. This is similar to how I would write it. You get the
benefits of optimization in `perlin^', while still accepting any real
numbers as inputs.

> > Yes, do this. The only other option is examining fully expanded code in
> > the Macro Stepper and rediscovering the Optimization Coach's advice on your
> > own, which would be un-fun.
> 
> 
> The Optimization Coach is really nice. I had to look up what the colors
> meant, but after that it's been most helpful.
> 
> Although there is a lot more red when using Real instead of Flonum, but the
> runtimes seem about the same. Is it doing more optimizations than it
> appears or is there still more room to eek out some additional performance?
> Changing Real to Float makes everything nice and green.

As I said above, the version of Optimization Coach that ships with the
current Racket release does not distinguish between optimizations in hot
code and optimizations in cold code. The former have a bigger impact on
performance than the latter.

If you're interested, you should try the newest version of Optimization
Coach. I'd be interested in knowing whether it provides better
recommendations for your program.

Vincent

Posted on the users mailing list.