How to use Flambda with dune in ocaml?

Solution 1:

Flambda is a configuration feature of the compiler, which is disabled by default (as of January 2022). To use it, you need to install a version of the compiler that enables this feature. It is very easy with opam, e.g.,

opam switch create myswitch ocaml-variants.4.13.0+options ocaml-option-flambda

It will create a new switch with the 4.13.0 version of the OCaml compiler and that has the flambda feature enabled. The general syntax is,

opam switch create <switch-name> ocaml-variants.<version>+options <options>...

You can enable several options, see opam search ocaml-options for all the options.

After you have installed the flambda version of OCaml, it will use flambda optimizations by default (but make sure that you're using the release version, as the default debug version disables some of the optimizations, including the cross-module optimization). Also, as usual, do not forget to activate your switch with eval $(opam env).

The flambda compiler has numerous configuration options that are thoroughly described in the manual. You may experiment with them to find some tradeoff between the compilation time and the performance of your application. You can set the options using flags stanza, e.g., (flags (:standard -rounds 5)). You can set the flags globally as well. Once you find the perfect set of flags, you can even use them to compile your upstream dependencies, using the OCAMLPARAM environment variable. Using this environment variable you can change the optimization parameters without interfering with the build scripts of other packages, e.g.,

export OCAMLPARAM='_,rounds=5,O=3,inline=100,inline-max-unroll=5'
# opam install your deps