I wish to export compiled functions for later use. This means that I do not want the compiled function to be recompiled every time I reload it. It also means that if my compiled function was for example Listable
, then the function should still be Listable
when I reload it.
Below I will present some attempts to save and reload the following function.
function =
Compile[{{x, _Real}}, Sum[Sin[Cos[-x^2*i]], {i, 1, 10^6}],
CompilationTarget -> "C", RuntimeAttributes -> {Listable},
Parallelization -> True];
Attempt using .wdx
file
SetDirectory[NotebookDirectory[]]
Export["compiled.wdx", function];
function[Range[10]] // AbsoluteTiming//First
(* 0.191019 seconds *)
Now after restarting the kernel, we get
SetDirectory[NotebookDirectory[]];
function2 = Import["compiled.wdx"];
function2[Range[10]] // AbsoluteTiming//First
(* 0.310031 seconds *)
Of course this difference in timing is unacceptable - it seems the function is now recompiled every time it is called.
Attempt using LibraryGenerate
Our example function function
accepts lists, because we used RuntimeAttributes -> {Listable}
function[{1, 0}]
(* {-0.2982909888387981, 841470.9848238959} *)
We now try to save this function as follows:
Needs["CCodeGenerator`"]
LibraryGenerate[function, "Myfun"]
And load it again:
function3 = LibraryFunctionLoad["Myfun", "Myfun", {Real}, Real]
There are two problems when using this method of exporting the function.
It seems that even if you do not compile to C code when you export as mentioned above it compiles to C code because if the function is not compiled to C code after loading it, it gets as fast as a function compiled to C code.
The more important issue is that now the function won't accept a list as its argument:
function3[{1, 0}]
LibraryFunction::cfsa: Argument {1,1} at position 1 should be a machine-size real number. >>
LibraryLink
. Or you can put the compilation command as an initialization cell to run when you open the notebook. $\endgroup$