MathGroup Archive 2002

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

Search the Archive

Re: Summing a list of real numbers

  • To: mathgroup at
  • Subject: [mg33444] Re: [mg33416] Summing a list of real numbers
  • From: gleam at (Paul)
  • Date: Thu, 21 Mar 2002 09:27:34 -0500 (EST)
  • Sender: owner-wri-mathgroup at


I've been using Tr[x] as an alternative to Apply[Plus, x] for long
time.  Though I can't conclusively explain why it's faster in your
application, I'm pretty sure it's related to the handling of packed
arrays though.  Try this little experiment:

lst = Table[Random[], {1000000}];
Tr[lst] // Timing
Plus @@ lst // Timing
lst = Developer`FromPackedArray[lst];
Tr[lst] // Timing
Plus @@ lst // Timing

After "unpacking" the data using Developer`FromPackedArray, Tr slows
way down, but most interestingly, Plus@@ actually becomes FASTER when
working on the "unpacked" data, to the point that evaluation time is
equal to or less than for Tr[lst] on the same unpacked data.




  In the course of working on an optimization problem that involves
summing large lists of real numbers, a colleague of mine came across
an interesting result. We compared the computational speed of
different methods for summing lists:

     (1) Apply[Plus, mylist]
      (2) Dot[mylist,ListofOnes], where ListofOnes is a list of of
size N of 1.0's

      (3) Tr[mylist], where Tr is the built-in matrix trace operator.

  Based on our tests (where list sizes range from 100,000 to 1,000,000
elements), Method (3) is far and away the fastest. On average (3) is
5x faster than Method (2), and over 70x faster than Method (1). 

  I was curious if anyone could offer an explanation.



  • Prev by Date: Re: newbie question - printing Pi
  • Next by Date: cleaner way to do Options (named arguments)
  • Previous by thread: Summing a list of real numbers
  • Next by thread: the fastest way to read binary files