       Re: SetDelayed and Evaluate

• To: mathgroup at smc.vnet.net
• Subject: [mg104487] Re: SetDelayed and Evaluate
• From: Bill Rowe <readnews at sbcglobal.net>
• Date: Sun, 1 Nov 2009 17:55:07 -0500 (EST)

```On 11/1/09 at 4:02 AM, insomnia.berlin at gmail.com (Peter) wrote:

>after years of experience with Mathematica I've got a simple (?)
>problem:

>When answering to a question on the student support forum (http://
>forums.wolfram.com/student-support/topics/21448/) I tried fo myself
>the folowing variants:

>f[z_?NumericQ]:=Compile[{{x,_Real}},x-x^2][z];
>g[z_?NumericQ]:=Evaluate[Compile[{{x,_Real}},x-x^2]][z];

>and got the following results:

>In:= Timing[Do[NMaximize[f[x],x],{1000}]]
>Out= {35.871,Null}

>In:= Timing[Do[NMaximize[g[x],x],{1000}]]
>Out= {35.962,Null}

>~1 ms per NMaximize is OK, because there are background-processes
>running.

>But I expect f to compile x-x^2 at every call to f and g to compile
>once on time of definition. Therefore I expected g to be
>significantly faster than f.

I don't understand why you expect different f and g to behave
differently. In both cases you use SetDelayed. So, in both cases
the stuff to the right gets evaluated on every call which
includes the Evaluate statement. I would expect there to be
definition of g. And while it is tempting to interpret your
timing results as supporting my expectation, there is also the
possibility the timing difference is simply due to measurement
uncertainties. The difference looks too small to be certain it
is significant.

Also, if the goal is to improve execution speed note:

In:= f[z_?NumericQ] := Compile[{{x, _Real}}, x - x^2][z]

In:= Timing[Do[NMaximize[f[x], x], {100}]]

Out= {8.39542,Null}

In:= g[x_?NumericQ] := x - x^2

In:= Timing[Do[NMaximize[g[x], x], {100}]]

Out= {5.5667,Null}

In:= h[x_] := x - x^2

In:= Timing[Do[NMaximize[h[x], x], {100}]]

Out= {4.95141,Null}

Not surprisingly, the less work you require the less time it
takes. I don't see any obvious way to use Compile to improve
execution speed here. If you use SetDelayed, the Compile
operation is done on every call. If instead you define:

y[x_] = Compile[{{x, _Real}}, x - x^2]

and then try NMaximize you will get an error since y[x] is no
longer an expression NMaximize can work with.

=46inally, it is worth noting the timing difference between y[x]
and h[x]:

In:= Timing[Total@Table[y[RandomReal[]], {1000000}]]

Out= {2.89152,166741.}

In:= Timing[Total@Table[h[RandomReal[]], {1000000}]]

Out= {2.48571,166678.}

The compiled version actually seems a bit slower on my system.
My experience with Mathematica is Compile is more trouble than
it is worth and seldom provides significant improvement on well
written Mathematica code.

```

• Prev by Date: Re: Problem with Screen Environment
• Next by Date: Re: Re: Dotted Plots
• Previous by thread: Re: SetDelayed and Evaluate
• Next by thread: Re: How to calculate a union