Tag Info

Hot answers tagged

56

Yes, but this only exists in version 8 and is undocumented: Compile`CompilerFunctions[] // Sort giving, for reference: {Abs, AddTo, And, Append, AppendTo, Apply, ArcCos, ArcCosh, ArcCot, ArcCoth, ArcCsc, ArcCsch, ArcSec, ArcSech, ArcSin, ArcSinh, ArcTan, ArcTanh, Arg, Array, ArrayDepth, Internal`Bag, Internal`BagPart, BitAnd, BitNot, BitOr, BitXor, ...


50

I'll just throw in a few random thoughts in no particular order, but this will be a rather high-level view on things. This is necessarily a subjective exposition, so treat it as such. Typical use cases In my opinion, Compile as an efficiency-boosting device is effective in two kinds of situations (and their mixes): The problem is solved most efficiently ...


35

Use these 3 components: compile, C, parallel computing. Also to speed up coloring instead of ArrayPlot use Graphics[Raster[Rescale[...], ColorFunction -> "TemperatureMap"]] In such cases Compile is essential. Compile to C with parallelization will speed it up even more, but you need to have a C compiler installed. Note difference for usage of C and ...


30

In addition to the answers given, you may tweak specific commands to give better performance. For example Part[] is a candidate for this. Part has to do bound checks. In time critical inner loops you can switch that off be using, Compiler`GetElement[] instead. Very cautious with this one. Another thing you might want to try (never needed this myself) is ...


26

A lot depends on how you write your code in Mathematica. In my experience, the rule of thumb is that the generated code will be efficient if the code inside Compile more or less resembles the code I would write in plain C (and it is clear why). Idiomatic (high-level) Mathematica code tends to be immutable. At the same time, Compile can handle a number of ...


25

In addition to Oleks list, there is of course a way to study what happens under the hood. f = Compile[{{x, _Integer, 1}}, Accumulate[x] ]; << CompiledFunctionTools` CompilePrint[f] (* 1 argument 1 Integer register 2 Tensor registers Underflow checking off Overflow checking off Integer overflow ...


23

I assume you need the list of compilable functions to make sure that all of your code will be properly compiled, and it won't take any speed penalties (that why I was looking for this information before). People have shown you how to print the compiled code and check that there are no calls to MainEvaluate in it. There is an alternative and simpler way of ...


21

The code as it is now looks very much FORTRAN style, which is fine. But Mathematica offers you a wide range of ways to make your code more readable, faster and easier to spot potential bugs. So let's go through through some of the possible ways to improve your code: Variable Naming I know that in languages like C and FORTRAN it's common to give variables ...


20

I don't have an answer but this is a bit hard to format in a comment. If runtime speed is your goal, I'd suggest using Compile with settings CompilationTarget->"C", CompilationOptions -> {"ExpressionOptimization" -> True, "InlineExternalDefinitions" -> True}, RuntimeOptions -> "Speed" I'm not certain about the inlining, and there may be ...


20

This might be an excellent candidate for ParallelTable; MakeFractal[f_, nx_, ny_, {cx_, cy_}, {rx_, ry_}] := Module[{pts}, DistributeDefinitions[nx, ny, cx, cy, rx, ry, f]; pts = ParallelTable[f[x + I y], {x, cx - rx, cx + rx, (2 rx)/nx}, {y, cy - ry, cy + ry, (2 ry)/ny}]; ArrayPlot[Reverse@pts, ColorFunction -> "TemperatureMap"] ] ...


20

I am somewhat reluctant to offer this as an answer since it is inherently difficult to comprehensively address questions on undocumented functionality. Nonetheless, the following observations do constitute partial answers to points raised in the question and are likely to be of value to anyone trying to write practical compiled code using Bags. However, ...


18

This is not an answer to your question, but it does address some of the issues with your code. In particular, it is just plain unreadable, and unreadable code cannot be maintained in any meaningful manner. If you came back to this even after a week of not using it, you would not understand how it works. Towards that end, I've simplified it quite a bit, just ...


17

Not a proper answer, but I just want to comment that the procedure carried out by @rcollyer can be automated to a large extent. Here is a code for a simplistic common subexpression eliminator: ClearAll[csub]; csub[expr_Hold, rules_List, limitCount_] := With[{newrule = Replace[ If[# =!= {} && #[[-1, -1]] > 1, #[[-1, 1]], {}] &@ ...


16

This is a tricky case indeed, because what you basically ask for is compile-time evaluation (macro-style). Generally, the answer is to use meta-programming, to assemble the compiled expression at run-time. The reason your attempt did not work is that the expression you want to evaluate is too deep for Evaluate to be effective. Solution using in-place ...


15

This is awful. It is one very typical example of "how to use Mathematica the wrong way*. OK, enough complaining. Let me give you one hint. Lets say you have a 500x500 and a 1000x1000 matrix and you want to copy the smaller one in the upper left corner of the larger one. We do this step 100 times. In your style this would go like m1 = RandomReal[{0, 1}, ...


15

Here is another compiled implementation: hammingDistanceCompiled = Compile[{{nums, _Integer, 1}}, Block[{x = BitXor[nums[[1]], nums[[2]]], n = 0}, While[x > 0, x = BitAnd[x, x - 1]; n++]; n ], RuntimeAttributes -> Listable, Parallelization -> True, CompilationTarget -> "C", RuntimeOptions -> "Speed" ]; This appears to ...


14

I believe there is such a list available but I can't remember the command off-hand. In the meantime, you can always load CompiledFunctionTools via. <<CompiledFunctionTools` And then use CompilePrint on a compiled function to see if MainEvaluate is present in the pseudocode. MainEvaluate tells us that something is going through the evaluator and ...


12

acl already posted the crucial information needed to solve this conundrum (i.e., the definition of Internal`CompileValues[LinearSolve]), but wishes to delete his post since he had not interpreted it to give the complete answer. Therefore I re-post the following observation along with a summary of what it means. The input, Internal`CompileValues[]; ...


12

Setting SetSystemOptions[ "CompileOptions" -> "CompileReportExternal"->True] will emit a message when parts of your function do not get compiled. After compilation, Needs["CompiledFunctionTools`"] followed by CompilePrint[cF] (with cF the function you have compiled will display some bytecode; looking for CopyTensor or MainEvaluate in that helps locate ...


12

If you use the setting CompilationTarget -> "C" (documentation: CompilationTarget) you get a function that is literally converted to C code and compiled: f = Compile[{{x, _Real}}, Sin[x] + x^2 - 1/(1 + x), CompilationTarget -> "C"]; Then you can actually export the C code and look at, or use ExportString to print it directly in Mathematica: ...


12

Note: instead of picking random element I just pick the first it runs into, random version at the end getCell = Compile[{{sp, _Integer, 2}, {i, _Integer}, {j, _Integer}, {x, _Integer}}, Block[{ n, m, k2, l2, cell}, {n, m} = Dimensions[sp]; cell = {i, j}; Do[(*This is the neighborhood *) k2 = Mod[i + k, n, 1]; l2 = Mod[j + l, m, 1]; ...


12

This seems to give a rather decent performance (final version with improvements by jVincent): Clear[getSubset]; getSubset[input_List,sub_List]:= Module[{inSubQ,sowMatches}, Scan[(inSubQ[#] := True)&,sub]; sowMatches[x_/;inSubQ@First@x] := Sow[x,First@x]; Apply[Sequence, Last@Reap[Scan[sowMatches, input], sub], {2}] ]; Benchmarks: n = ...


12

If you look at the generated code (CompilePrint, for example), the procedure is as follows: All the program's constants are placed into separate registers (regardless of their location in the program, they can be in the r.h.s.of variable initialization in scoping constructs, or they can be statements in their bodies. Actually, same constants found in ...


11

About your question regarding the definition of the type of local variables in Compile, Compile has an optional third argument that allows you do this in the same manner you specify arguments. It helps the compiler solve some type ambiguity issues sometimes as by default a local variable is considered a Real number. This can be the case if a local variable ...


11

Assuming you know the dimensions of the pieces that you want to come out you can always add a second argument to Internal`StuffBag that indicates the rank of the elements going in. The result is still flat so you have to partition after the fact. cf = Compile[{}, Module[{bag = Internal`Bag[]}, Do[Internal`StuffBag[bag, {i, i, i}, 1], {i, {0, 1, 2, 3}}]; ...


11

Try this: G = 4.49*^3; M = 1.; S = 1.; \[Epsilon] = 2.; With[ {G = G, M = M, S = S, \[Epsilon] = \[Epsilon]}, SAcceleration = Compile[{{SPosition, _Real, 1}}, (-G (M + S))/(SPosition.SPosition + \[Epsilon]*\[Epsilon])^(3/ 2) SPosition]; SAcceleration2 = Compile[{{SPosition, _Real, 1}}, Module[{GG = G, MM = M, SS = ...


11

The reason for this message is that the compiled function is called with the symbolic argument SR[n] in the definition of the recurrence relation: SAcceleration[SR[n]] CompiledFunction::cfta: "Argument SR[n] at position 1 should be a rank 1 tensor of machine-size real numbers." -((8980. SR[n])/(4. + SR[n].SR[n])^(3/2)) The recurrence is then ...


11

It's not you, it's Mathematica. You are not expected to know this, but basically, in compiled code, ReplacePart merely acts as syntactic sugar for setting a part, i.e.: l = Range[3]; ReplacePart[l, 2 -> 0] (* -> {1, 0, 3} *) would be compiled (but see below) into exactly the same bytecode as l = Range[3]; Block[{l = l}, l[[2]] = 0; l] (* -> {1, ...


10

As Leonid already commented, your code should not be especially slow. However one reason why your code may be slow is that you use Part to extract values, do some calculations and then insert the result. I would try using a wholesale approach and calculate all nodes at the same time by doing, e.g. (may need tweaking since I don't know the structure of your ...


10

I know you explicitly asked for an answer using Compile but as stated in my comment, I'm not sure this is required. Additionally, I don't think it is possible as you expect it. Your list is a ragged array, which means it is a non-rectangular tensor. To my knowledge it is not possible to use it with Compile. Even the simplest example fails, which does nothing ...



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