Thread: The fastes way to sum array of integers

The fastes way to sum array of integers

From
aasat
Date:
Hi,

I sum values of array integers by query

select sum(t)
     from unnest(array[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]) as t
     cross join generate_series(1, 1000000);

Total runtime: 10020.699 ms

But simmilar method to count array's elements is dramatically faster

select sum(array_length(array[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0], 1))
from generate_series(1, 1000000)

Total runtime: 464.042 ms


It's as fast as simple query!

select sum(1) from generate_series(1, 1000000)
"Total runtime: 462.687 ms"


It is possible that function e.g. array_sum written in C is as fast as
bult-in array_length?


regards
Wojciech





--
View this message in context:
http://postgresql.1045698.n5.nabble.com/The-fastes-way-to-sum-array-of-integers-tp5736771.html
Sent from the PostgreSQL - general mailing list archive at Nabble.com.


Re: The fastes way to sum array of integers

From
Pavel Stehule
Date:
2012/12/16 aasat <satriani@veranet.pl>:
> Hi,
>
> I sum values of array integers by query
>
> select sum(t)
>      from unnest(array[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]) as t
>      cross join generate_series(1, 1000000);
>
> Total runtime: 10020.699 ms
>
> But simmilar method to count array's elements is dramatically faster
>
> select sum(array_length(array[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0], 1))
> from generate_series(1, 1000000)
>
> Total runtime: 464.042 ms
>
>
> It's as fast as simple query!
>
> select sum(1) from generate_series(1, 1000000)
> "Total runtime: 462.687 ms"
>
>
> It is possible that function e.g. array_sum written in C is as fast as
> bult-in array_length?
>

yes - specialized function can be significantly faster - and
aggregation can be calculated with significantly less iterations.

Regards

Pavel



>
> regards
> Wojciech
>
>
>
>
>
> --
> View this message in context:
http://postgresql.1045698.n5.nabble.com/The-fastes-way-to-sum-array-of-integers-tp5736771.html
> Sent from the PostgreSQL - general mailing list archive at Nabble.com.
>
>
> --
> Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
> To make changes to your subscription:
> http://www.postgresql.org/mailpref/pgsql-general