Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
2  
See here for some germane details in Leonid's answer. –  rasher May 30 at 9:15

1 Answer 1

up vote 6 down vote accepted

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.

share|improve this answer
    
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 to Block[{c=1},a=Somefunction[b];...]? –  Ziofil May 30 at 23:18
    
@Ziofil It doesn't matter whether you have SomeFunction[...] or ` number there. In your second example a is not localized, which will cause the performance problem I mentioned. –  Szabolcs May 31 at 2:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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