Hot answers tagged

34

Okay, this is a bit of an embarassment. Here is a very small modification of the original code. I simply made explicit option settings, made a denominator to Sin explicitly real, that kind of thing. My tests show the same timing as the original, give or take an iota. ie = 200; ez = ConstantArray[0., {ie + 1}]; hy = ConstantArray[0., {ie}]; fdtd1d = ...


33

Leonid Shifrin has already given an excellent answer for the question but it's so… long and may be frustrating for someone just beginning to learn the usage of Compile so I decided to post this as an answer. Recently (OK… actually it's more than a year ago) I found that Ted Ersek's Mathematica tricks(.nb version can be found here) contains a brief but ...


32

This is because Table automatically compiles its argument above a certain length limit. SystemOptions["CompileOptions" -> "TableCompileLength"] (* {"CompileOptions" -> {"TableCompileLength" -> 250}} *) It does not seem to realize that the code modifies global variables because that behaviour is hidden behind code. Notice that the following both ...


27

First off, your function is very simple without any hard number-crunching, so it will always be hard to get a large speedup for the compiled version. Secondly, your Parallelization option for Compile is useless because it doesn't do any parallelization this way. Let me give slightly changed versions of your examples and explain how you can achieve a large ...


26

The default SumCompileLength is 250. You can increase this number for example to 500 using SetSystemOptions["CompileOptions" -> {"SumCompileLength" -> 500}] or to infinity using SetSystemOptions["CompileOptions" -> {"SumCompileLength" -> ∞}] What is "SumCompileLength" for? For sums with a finite number of at least "SumCompileLength" elements ...


26

It is important to Compile that it has always the same return type, no matter what happens at runtime. Note that Which returns Null as default value. Since the return value of the function is meant to be a 4-vector in some cases, we have to assign also a 4-vector (e.g., {0., 0., 0., 0.}) as default return value of Which. So this should work: ...


26

One of the biggest differences between main kernel evaluation and compiled evaluation in the "Wolfram Virtual Machine" (WVM) is that in the kernel, arbitrary expressions are allowed that are rewritten according to pattern-matching rules and in the WVM things are much more restricted and predictable. For instance, the types of all variables are ...


21

Yes, there is! Mathematica creates a LibraryFunction when compiling to C, but puts it in a temporary directory. If you can recover the library, you can load it as often as you like! First let's define the function as in the question: generatef[opt_] := Compile[{}, Module[{j = 0}, Do[j++, {i, 10^8}]; j], CompilationTarget -> opt]; f2 = generatef["C"]; ...


20

Another option to the answer posted by Andy Ross cropped up in a recent question of mine about corrupting an image with Poisson noise. In my own answer, I made use of LibraryLink to utilise the distributions built into C++. This was especially useful in my case because Poisson noise in an image otherwise relies on a call to RandomVariate for each pixel (...


19

Looking at CompilePrint[compiledGlynnAlgorithm], there are some lines with CopyTensor in it which aren't really needed. There's also a few CoerceTensor lines in there when it might be faster to just coerce the integer matrix once at the beginning. By slightly adjusting the function, all instances of CopyTensor and CoerceTensor go away, giving a small ...


18

Congratulations! You find one of subnormal positive double :) Another example f = Compile[{{t, _Real}}, 2.0^t]; f[-1074] f[-1075] 5.*10^-324 0 MachineNumberQ@f[-1074] True This doesn't mean that CompiledFunction can work with arbitrary-precision numbers. Update Normally Mathematica prevents such numbers 2.^-1074. % // MachineNumberQ 4.940656458413*...


18

No, it is not possible. With code converted to a LibraryLink library by way of Compile you are limited to using functions that either can be expressed directly in C, or exist in the runtime library; unfortunately, FindFit is not included in either category. When present in code passed to Compile, FindFit results in a call back to the top level, and it is ...


18

Using Compile with CompilationTarget->"C" does generate C-Code to be compiled in a generalized way, the resulting code will contain some overhead due to that compared to hand-written code which can easily explain any difference in runtimes. Even for cases where that overhead is minimal or non-existent automatic code generation will always produce ...


18

Based on the experience obtained here: friction = Compile[{{v, _Real}, {vt, _Real}}, If[v > vt, -v*3.0, -vt*3.0*Sign[v]]]; simulateSpring = Compile[{{x0, _Real}, {t, _Real}, {dt, _Real}, {vt, _Real}}, Module[{τ, times, positions, v = 0.0, a = 0.0, x = x0}, τ = t; times = Range[0.0, t, dt]; positions = Table[0.0, {Length@times}]; ...


16

(This is not an answer, but only a phenomenon I observed. And I think it might be a bug.) I think in version 9, Mathematica fails to compile the Fold for $n\geq 166$ where $n$ is the integer number in Range. The precise threshold may be different from OS to OS, but I suspect this phenomenon exists in all version 9. Note the default "FoldCompileLength" is ...


16

Compilation of Total As pointed out in a comment, it seems that the compensated summation form of Total can't be compiled. You can check this using CompilePrint - note the call to MainEvaluate. Needs["CompiledFunctionTools`"] CompilePrint@f2 (* from your question *) Summation in Mathematica There seem to be plenty of options for summing a list in ...


16

Here is the original code. logisticMap[x0_, μ_, n_] := Module[{i}, RecurrenceTable[{x[i + 1] == μ x[i] (1 - x[i]), x[1] == x0}, x, {i, 1, n}]] We'll show an example so we can test other variants for correctness. In[316]:= logisticMap[0.1, 3.55, 10] Out[316]= {0.1, 0.3195, 0.7718401125, 0.625165483988, 0.831884285744, \ 0.49647751411, 0....


16

Extended comment.. I've never come across specifics of what Compile[] specifically does. That said, a definition re: programming languages in general provides some insight/understanding: Compiling is the transformation from Source Code (human readable) into machine code (computer executable). ... A compiler takes the recipe (code) for a new program (written ...


15

The reason for this behavior is that autocompilation always uses settings equivalent to "RuntimeOptions" -> {"Quality", "WarningMessages" -> False}. As previously noted in Silvia's answer, the automatic compilation is invoked for input exceeding SystemOptions["CompileOptions" -> "FoldCompileLength"] (* {"CompileOptions" -> {"FoldCompileLength"...


15

It appears that LibraryFunction occurs if the function being called inside the other compiled function is a function that has been compiled to C, provided this function has been called with the right type of arguments. It seems that in other cases there is a CompiledFunctionCall. As pointed out by Simon Woods in the comments below, there is a type mismatch ...


15

Simple solution There is an easier solution than the one I gave almost 2 years ago. In principle, you wrap your library function inside another CompiledFunction that is listable. Let the code speak: fun = LibraryFunctionLoad["demo", "demo_I_I", {Integer}, Integer]; With[{fc = fun}, funListable = Compile[{{i, _Integer, 0}}, fc[i], RuntimeAttributes -&...


15

Preface I've put a FaddeevaM package on my GitHub account that will do all that follows automatically. It is a full package that exposes all (and not only the Faddeeva $w$) functions for Mathematica users. I have tested the package under Linux (10.3 and 11.1) and Mac OS X (11.1) and it seems to work. I will put further documentation in the GitHub ...


15

Compile is considered a scoping construct by the outer With, and its bindings are protected. This will work: With[{args = {{x, _Real}}}, Hold[Compile @@ Hold[args, x + 2]]] or this (if you don't want to keep Apply in code): Unevaluated[ With[{args = {{x, _Real}}}, Hold[Compile[args, x + 2]]] ] /. Compile -> $compile /. $compile -> Compile ...


15

No expert on this, but will share what little I know about this. This is based on my understanding of the video Wolfram Language Version 12.3 Sneak Peek with Jon McLoone Here is a link What happens now in 12.3 is that there are many Mathematica functions that automatically have Compile wrapped around them, behind the scene, when you call them. So first ...


14

To my knowledge, one of the situations where the third argument of Compile is required is when your compiled code needs to make a MainEvaluate call. Often, the situation is the other way around: you have code and you try to compile it down completely, so that no MainEvaluate call is necessary. Honestly, most of the questions about Compile here deal to some ...


14

Figured it out. The key was working out that if I included "ShellOutputFunction"->Print in the $CCompiler list, compilation of the function would show me what the shell was doing. Thus I learned that it was failing to find libgcc_s. I found libgcc_s.a in C:\MinGW-64\lib. I created a system environment variable LIBRARY_PATH with value C:\MinGW-64\lib, and ...


14

Almost 3 years later.. The problem lies in the Label instruction. What happens when you have code that contains labels and gotos is that the Goto instructions are successfully converted to valid jump op-codes. The labels, however, are just, well, labels. They don't even have a meaning, because jumps in compiled code are converted to jumps to a line number. ...


14

This is not a full answer, but too long for a comment. We can try to look at the C code that Mathematica generates. Needs["CCodeGenerator`"] cf = Compile[{{n, _Integer}}, RandomReal[1, n]] CCodeStringGenerate[cf, "fun"] Excerpt from the output: ... FP0 = funStructCompile->getFunctionCallPointer("RandomReals"); ... err = FP0(libData, 3, FPA, FPA[3]);/*...


14

I think this is because a in your code represents a rank 10 tensor. If you want to use a as a vector, then I think it would be safeConv =Compile[{{a, _Complex, 1}, {b, _Real}}, If[b > 1, a[[1]], 0]] Otherwise, if a is a rank 10 tensor, then something like this safeConv = Compile[{{a, _Complex, 10}, {b, _Real}}, If[b > 1, a[[1, 1, 1, 1, 1, 1, 1, ...


14

If you declare the type of DuplicateFreeQ, it works consistently (in V11.1.1). cf = Compile[{{n, _Integer}}, Module[{good}, good = True; If[DuplicateFreeQ[{}] && n == 15, good = False]; good], {{DuplicateFreeQ[_], True | False}} ]; One really ought to declare the type of DuplicateFreeQ, but it's as yet unclear to me why ...


Only top voted, non community-wiki answers of a minimum length are eligible