'How to use Flambda with dune in ocaml?

I'm doing a project in which I need to optimize my code as much as I can because it takes hours to run with a normal compilation.

I was told to use Flambda, but I didn't find anything on the internet on how to use it with dune.

I'd appreciate instructions to follow / resource to read.



Solution 1:[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.1+options ocaml-option-flambda

It will create a new switch with the 4.13.1 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-option 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,O3=1,inline=100,inline-max-unroll=5'
# opam install your deps

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1