3
$\begingroup$

I was very interested in the answer of How to avoid “CopyTensor” in compile function with external call? and tried it on my own example below. And it does not work. Just curious why?

mvMu = With[{Part = Compile`GetElement}, 
  Compile[{{i, _Integer}, {j, _Integer, 1}}, 
   Module[{sum = 0}, Do[If[j[[k]] > i, sum++], {k, Length[j]}]; sum], 
   CompilationTarget -> "C", "RuntimeOptions" -> "Speed"]
  ]


mvMuS = With[{mvMu = mvMu, Part = Compile`GetElement},
  Compile[{{i, _Integer, 1}, {j, _Integer, 1}}, 
   Module[{sum = 0}, Do[sum = sum + mvMu[j[[k]], i], {k, Length[j]}]; 
    sum], CompilationTarget -> "C", 
   CompilationOptions -> {"ExpressionOptimization" -> True, 
     "InlineCompiledFunctions" -> True, 
     "InlineExternalDefinitions" -> True}, 
   "RuntimeOptions" -> "Speed"]]

The code still contains CopyTensor:

CompiledFunctionTools`CompilePrint[mvMuS]

[...]

4 goto 21

5 I6 = GetElement[ T(I1)1, I5]

6 T(I1)2 = CopyTensor[ T(I1)0]]

[...]

$\endgroup$
2
$\begingroup$

Just leave away the inlining options in CompilationOptions:

mvMu = With[{Part = Compile`GetElement}, 
  Compile[{{i, _Integer}, {j, _Integer, 1}}, 
   Module[{sum = 0}, 
    Do[If[j[[k]] > i, sum++], {k, Length[j]}]; 
    sum
   ], 
   CompilationTarget -> "C", 
   "RuntimeOptions" -> "Speed"
   ]
  ]


mvMuS = With[{
   mvMu = mvMu,
   Part = Compile`GetElement
   },
  Compile[{{i, _Integer, 1}, {j, _Integer, 1}},
   Module[{sum = 0},
    Do[sum = sum + mvMu[j[[k]], i], {k, Length[j]}];
    sum
    ], 
    CompilationTarget -> "C", 
    "RuntimeOptions" -> "Speed"
    ]
   ]

Now, we have

CompiledFunctionTools`CompilePrint[mvMuS]

[...]

1 I1 = I0

2 I4 = Length[ T(I1)1]

3 I5 = I0

4 goto 9

5 I6 = GetElement[T(I1)1, I5]

6 I7 = LibraryFunction[<>, compiledFunction20, {{Integer, 0, Constant}, {Integer, 1, Constant}}, Integer][ I6, T(I1)0]]

7 I6 = I1 + I7

8 I1 = I6

9 if[ ++ I5 <= I4] goto 5

10 Return

It should be clear by now that the automatic inlining by Mathematica is not that great... which is why I never use it.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.