Two weird performance issues in Mathematica

FIRST PROBLEM

I calculated how long it will take to calculate the following operators (where V [x] is an intensive function call):

Alice     = Table[V[i],{i,1,300},{1000}];
Bob       = Table[Table[V[i],{i,1,300}],{1000}]^tr;
Chris_pre = Table[V[i],{i,1,300}];
Chris     = Table[Chris_pre,{1000}]^tr;

Alice, Bob and Chris are the same matrices, designed for 3 slightly different ways. I find that Chris computes 1000 times faster than Alice and Bob.

It is not surprising that Alice computes 1000 times slower, because, naively, the function V needs to be called another 1000 times than when calculating Chris. But it is very surprising that Bob is so slow as he is exactly calculating with Chris, except that Chris stores the intermediate step Chris_pre.

Why is Bob evaluating so slowly?


SECOND PROBLEM

Suppose I want to compile a function in Mathematica form

f(x)=x+y

"y" - , ( , ). y y = 7.3,

f1=Compile[{x},x+y]
f2=Compile[{x},x+7.3]

f1 50% , f2. Mathematica "y" "7.3", f1 , f1 , f2?


EDIT:

:

f1=ReleaseHold[Hold[Compile[{x},x+z]]/.{z->y}]

...

+5
3

, , !

- , , , . Bob , Table Table. Trace:

Trace[Table[Table[i, {i, 1, 3}], {3}]]

{
Table[Table[i,{i,1,2}],{2}],
{Table[i,{i,1,2}],{i,1},{i,2},{1,2}},{Table[i,{i,1,2}],{i,1},{i,2},{1,2}},
{{1,2},{1,2}}
}

, , Trace on Table , . , Mathematica , , , - . , , :

Transpose[Table[Evaluate[Table[V[i],{i,1,300}]],{1000}]]

, , .

Evaluate, , , ( , Held):

f1 = Compile[{x}, Evaluate[x + y]];

With:

With[{y=7.3},
    f1 = Compile[{x}, x + y];
]

, y , :

y = 7.3;
With[{z = y},
    f1 = Compile[{x}, x + z];
]

Mathematica, , , , !

+5

, , ConstantArray Mathematica 6 . Table[expr, {50}] , .

ConstantArray . , :

ConstantArray[Table[Pause[1]; i, {i, 5}], {50}] ~Monitor~ i

Table <5 → - Pause[1], , , 50 .

+2

Chris_pre? , , , . ChrisPre. .

The second problem Compilation has a number of complex limitations on its use. One of the problems is that you cannot reference global variables. The construction C proposed here, which has already been proposed. If you want to learn more about compilation, check out Ted Ersek's tricks: http://www.verbeia.com/mathematica/tips/Tricks.html

+1
source

All Articles