Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2008

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

Search the Archive

Re: Performance of Array Addition

  • To: mathgroup at smc.vnet.net
  • Subject: [mg90964] Re: Performance of Array Addition
  • From: "Jean-Marc Gulliet" <jeanmarc.gulliet at gmail.com>
  • Date: Fri, 1 Aug 2008 02:58:49 -0400 (EDT)
  • References: <g6rnv9$7lj$1@smc.vnet.net> <489189A1.2000307@gmail.com>

Jeremy wrote:

> Let there be, for example, an array of reals with dimensions
> {d1,d2,3}.
>
> I have noticed that the command
>
> array[[All,All,1]] + array[[All,All,2]] + array[[All,All,3]];
>
> is much faster than
>
> Map[Total, array, {2}];
>
> even though they return the same answer.
>
> The advantage of Map[Total, array, {2}] is that it allows arrays of
> dimension {d1,d2,d3}, with d3 arbitrary.
>
> Is there a way to get closer to the speed advantages of hand-coding
> the addition of the final dimension, while
> allowing the number of elements in the final dimension to be
> arbitrary?

Why not using the second argument of Total[]?

   Total[array, {3}]

The above expression is scalable and on average three times faster
than the hand-coded solution.

In[1]:= array = RandomReal[{-1, 1}, {100, 50, 3}];
Timing[tot1 = array[[All, All, 1]] + array[[All, All, 2]] +
          array[[All, All, 3]]; ][[1]]
Timing[tot2 = Map[Total, array, {2}]; ][[1]]
Timing[tot3 = Total[array, {3}]; ][[1]]
tot1 == tot2 == tot3

Out[2]= 0.00095

Out[3]= 0.010702

Out[4]= 0.000432

Out[5]= True

In[6]:= Table[(array = RandomReal[{-1, 1}, {100, 50, 3}];
 t1 = Timing[array[[All, All, 1]] + array[[All, All, 2]] +
            array[[All, All, 3]]; ][[1]];
 t2 = Timing[Map[Total, array, {2}]; ][[1]];
 t3 = Timing[Total[array, {3}]; ][[1]];
 {t1 , t2 , t3}), {10}]

Out[6]= {{0.000772, 0.009676, 0.000262}, {0.000771, 0.009517,
 0.000257}, {0.000739, 0.009531, 0.000262}, {0.000794, 0.00963,
 0.00026}, {0.000766, 0.009561, 0.000284}, {0.000812, 0.009681,
 0.000264}, {0.00074, 0.009579, 0.000261}, {0.000823, 0.009585,
 0.000266}, {0.000751, 0.009764, 0.00029}, {0.000807, 0.009716,
 0.000276}}

In[7]:= Mean[%]

Out[7]= {0.0007775, 0.009624, 0.0002682}

Regards,
-- Jean-Marc


  • Prev by Date: Re: When is a List not a List?
  • Next by Date: Re: Re: When is a List not a List?
  • Previous by thread: Re: Performance of Array Addition
  • Next by thread: Re: Performance of Array Addition