When is there an advantage to using Block
in Compile
? For instance, if I have a multiple-step code, how do I decide which variable assignments I should put into the first argument of Block[]
? Is it unwise to have functions being evaluated in there?
-
2$\begingroup$ See here for some germane details in Leonid's answer. $\endgroup$– ciaoCommented May 30, 2014 at 9:15
1 Answer
Block
(or Module
) is used for creating local variables in Compile
. (When used with Compile
they're equivalent.) You need to use them whenever you need to use any variables in compiled code.
Example
The following code does not localize y
:
cf = Compile[{x},
y = x*x;
y*y
]
Since y
is not localized to the body of Compile
, it is treated as a global variable, and will trigger calling back to the main evaluator. The practical consequence of this is that the program will run very slowly: the evaluation of y
, or any assignments to y
, will not be compiled. The function will still work, but it will not be fast because only certain parts will be compiled.
CompilePrint
gives
1 V17 = MainEvaluate[ Function[{x}, y = x x][ R0]]
2 R1 = MainEvaluate[ Function[{x}, y][ R0]]
3 R2 = MainEvaluate[ Function[{x}, y][ R0]]
4 R1 = R1 * R2
5 Return
The correct way to write this is
cf = Compile[{x},
Block[{y},
y = x*x;
y*y
]
]
Now y
is localized and the function can be fully compiled, so it will run much faster.
1 R1 = R0 * R0
2 R2 = R1 * R1
3 Return
Note: It does not matter whether you use
Block[{var = 1},
...
]
or
Block[{var},
var = 1;
...
]
They have the same effect.
-
$\begingroup$ Thanks, I learned something new! How about function evaluation within the first argument of Block? Does it ever make sense to compile
Block[{a=SomeFunction[b],c=1},...]
with respect toBlock[{c=1},a=Somefunction[b];...]
? $\endgroup$– ZiofilCommented May 30, 2014 at 23:18 -
$\begingroup$ @Ziofil It doesn't matter whether you have
SomeFunction[...]
or ` number there. In your second examplea
is not localized, which will cause the performance problem I mentioned. $\endgroup$– SzabolcsCommented May 31, 2014 at 2:12