       Re: Compile and arrays

• To: mathgroup at smc.vnet.net
• Subject: [mg114205] Re: Compile and arrays
• From: Daniel Lichtblau <danl at wolfram.com>
• Date: Sat, 27 Nov 2010 03:35:49 -0500 (EST)

```
----- Original Message -----
> From: "Eric Michielssen" <emichiel at eecs.umich.edu>
> To: mathgroup at smc.vnet.net
> Sent: Friday, November 26, 2010 4:30:06 AM
> Subject: [mg114187] Compile and arrays
> Compiled functions that act on subarrays of supplied arrays often run
> very
> slow.
>
> As an example, consider the following two routines "Ctest" (compiled)
> and
> "test" (standard mathematica). They do the same, namely extract the
> first
> row from matrices a and b, and add them.
>
> Ctest = Compile[{{a,_Real,2},{b,_Real,2}}, Module[{c},c = a[] +
> b[];Return[c]]];
> test[a_,b_]:=Module[{c},c = a[] + b[];Return[c]];
>
> Oftentimes, Ctest is two orders of magnitude slower than test,
> implying that
> the routine lacks information on the size of the two matrices to loop
> fast.
>
> Is there a remedy/workaround for this in Mathematica 8?
>
> Thanks,
> Eric Michielssen

I'm not sure under what circumstances you are seeing this, that is, what is the cause of the relative slowdown. Could be lack of packed array input. Some experimenting indicates the example below might qualify.

In:= n = 100;
a = N[RandomInteger[1, {n, n}], 20];
b = RandomReal[1, {n, n}];

In:= Timing[Do[Ctest[a, b], {1000}]]
Timing[Do[test[a, b], {1000}]]

Out= {3.369, Null}

Out= {0.063, Null}

If this is what you encounter, the workaround is that you may need to protect against inputs that are not packed arrays (can check this with Developer`PackedArrayQ).

alltest[a_, b_] :=
If[! Developer`PackedArrayQ[a] || ! Developer`PackedArrayQ[b],
test[a, b], Ctest[a, b]];

I'll ask around to see if there are switch settings that would make Compile not spend time packing its input (which I am assuming is the bottleneck). I tried the one below but it did not help in this instance.

SetSystemOptions[
"CompileOptions" -> {"CompileAllowCoercion" -> False}];

Daniel Lichtblau
Wolfram Research

```

• Prev by Date: Re: understanding code
• Next by Date: Why are my 3D plots blue?
• Previous by thread: Compile and arrays
• Next by thread: Can't read a package