MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Efficiency and ReplacePart?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg85925] Re: [mg85896] Efficiency and ReplacePart?
  • From: Carl Woll <carlw at wolfram.com>
  • Date: Thu, 28 Feb 2008 02:42:50 -0500 (EST)
  • References: <200802270923.EAA15990@smc.vnet.net>

W. Craig Carter wrote:

>If someone can answer the following question, I will have 
>learned something about efficiency in mathematica...
>
>I'd like each second part of a list to a zero-list:
>
>ftemp = Table[{RandomReal[1, {2}], RandomReal[1, {2}]}, {50000}];
>
>Compare:
>1)
>Timing[ftemp /. {{a_, b_}, {c_, d_}} :> {{a, b}, {0, 0}}][[1]]
>
>2)
>Timing[Map[(# = {#[[1]], {0, 0}} &), ftemp]][[1]]
>
>3) Timing[Map[ReplacePart[#, 2 -> {0, 0}] &, ftemp]][[1]]
>
>(*
>or if you like:
>times[n_] :=
>  Module[{ftemp =
>     Table[{RandomReal[1, {2}], RandomReal[1, {2}]}, {n}]},
>   {Timing[ftemp /. {{a_, b_}, {c_, d_}} :> {{a, b}, {0, 
>0}}][[1]],
>    Timing[Map[(# = {#[[1]], {0, 0}} &), ftemp]][[1]]}]
>
>ListPlot[Table[times[i], {i, 100, 10000, 100}]]
>*)
>
>
>1 is faster than 2 is faster than 3. Why?
>
>Craig
>
>  
>
This doesn't answer your question, but if you are working with large 
data sets you should turn them into packed arrays and make sure they 
stay packed. So, if instead of replacing the second column with {0,0} 
you wanted to replace it with {0.,0.}, then a much faster technique is 
the following. First use:

ftemp = RandomReal[1, {50000, 2, 2}];

so that you create a packed array.

In[144]:= Developer`PackedArrayQ@ftemp

Out[144]= True

Then:

In[145]:= (gtemp = ftemp;
   gtemp[[All, 2]] = ConstantArray[0., Dimensions[gtemp[[All, 2]]]];
   r1 = gtemp); // Timing

Out[145]= {0.016, Null}

Compare with:

In[146]:= Timing[r2 = ftemp /. {{a_, b_}, {c_, d_}} :> {{a, b}, {0, 
0}}][[1]]

Out[146]= 0.265

Carl Woll
Wolfram Research


  • Prev by Date: Re: Version 6.0.2
  • Next by Date: Re: Version 6.0.2
  • Previous by thread: Efficiency and ReplacePart?
  • Next by thread: Re: Efficiency and ReplacePart?