Message Boards Message Boards

0
|
5231 Views
|
3 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Accumulate slow with units.

Dear All,

I often use Accumulate, but found that it is very slow once you accumulate a list with units.

You would expect that adding 500 lengths up would take a fraction of a second:

AbsoluteTiming[Accumulate[Quantity[RandomReal[1, {500}], "Meters"]];]
{4.29581, Null}

However this takes a solid 4.3 seconds on my macbook pro retina!

Something without units goes very fast:

AbsoluteTiming[Accumulate[RandomReal[1, {500}]];]
{0.00002, Null}

Just a few micro-seconds!

Ok, so what if we get the number, get the magnitude, accumulate it, and give it back the units?

anums=bnums=Quantity[RandomReal[1,{500}],"Meters"];
AbsoluteTiming[
 anums=Accumulate[anums];
]
AbsoluteTiming[
 bnums=QuantityMagnitude[bnums,"Meters"];
 bnums=Accumulate[bnums];
 bnums=Quantity[bnums,"Meters"];
]
{4.30476,Null}
{0.032635,Null}

So over a 100x faster than the built-in Accumulate with units! I guess there is some checking done that slows down everything a lot (too much!)

Anyone another solution? Or some option to pass to Accumulate?

POSTED BY: Sander Huisman
3 Replies

Hmm indeed, that is also fast! Really strange! Rest@FoldList[Plus,0,#]& is not so neat as Accumulate though... I was thinking there might be a hidden option you could give to Accumulate to speed things up (disable unit-checking or so...).

Thanks for the answer! works already a lot faster!

POSTED BY: Sander Huisman

I don't know hidden option for Accumulate. But you can also speed up calculations even more using data[[;;,1]] instead of QuantityMagnitude. You can use this if you know that all data points are in the same unit.

Quantity[Accumulate[data[[;; , 1]]], "Meters"]; // AbsoluteTiming
{0.000800182, Null}
POSTED BY: Alexey Golyshev

From Documentation:

Accumulate[list] is effectively equivalent to Rest[FoldList[Plus,0,list]]

data = Quantity[RandomReal[1, {500}], "Meters"];

Rest@FoldList[Plus, 0, data]; // AbsoluteTiming
{0.0273921, Null}
POSTED BY: Alexey Golyshev
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract