# Mapslices and cumsum

**URL:** <https://discourse.julialang.org/t/mapslices-and-cumsum/10422>\
**Category:** Performance\
**Created:** [April 18, 2018, 10:21pm UTC](https://discourse.julialang.org/t/mapslices-and-cumsum/10422 "2018-04-18T22:21:26Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![gideonsimpson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gideonsimpson/32/1928_2.png) [@gideonsimpson](https://discourse.julialang.org/u/gideonsimpson)\
**Post date:** [April 18, 2018, 10:21pm UTC](https://discourse.julialang.org/t/mapslices-and-cumsum/10422/1 "2018-04-18T22:21:26Z")

</div>

I’m finding that the following code grinds my machine to a halt:

```julia
n=10^6;
X = randn(1,n);
function V(x)
    return 0.5 * dot(x,x);
end
avgX = cumsum(mapslices(V,X,1))./(1:n);

```

And by halt, I mean, I had to do a hard reset on one computer.

In contrast, the following code works just fine:

```julia
n=10^6;
X = [randn(1) for i=1:n]
function V(x)
    return 0.5 * dot(x,x);
end
avgX = cumsum(V.(X))./(1:n);

```

---

<div class="post-metadata">

**Author:** ![cortner](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cortner/32/204_2.png) [@cortner](https://discourse.julialang.org/u/cortner)\
**Post date:** [April 19, 2018, 2:58am UTC](https://discourse.julialang.org/t/mapslices-and-cumsum/10422/2 "2018-04-19T02:58:29Z")

</div>

The problem is that `cumsum(mapslices(V,X,1))` generates a row vector, while `(1:n)` is interpreted as a column vector. The `./` generates a 1e6 x 1e6 dense matrix. What you want is

```julia
avgX = cumsum(mapslices(V, X, 1))./((1:n)')

```

HOWEVER, this is still _much_ slower than your second version, which is counter-intuitive for me. Maybe somebody else can explain.

---

<div class="post-metadata">

**Author:** ![oschulz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oschulz/32/2998_2.png) [@oschulz](https://discourse.julialang.org/u/oschulz)\
**Post date:** [April 22, 2018, 10:03am UTC](https://discourse.julialang.org/t/mapslices-and-cumsum/10422/3 "2018-04-22T10:03:13Z")

</div>

> [@cortner](#):
>
> avgX = cumsum(mapslices(V, X, 1))./((1:n)')
> 
> HOWEVER, this is still much slower than your second version, which is counter-intuitive for me. Maybe somebody else can explain.

Shameless advertisement: You can use UnsafeArrays.@uviews instead of mapslices:

```julia
using UnsafeArrays
X = randn(1,n)
@uviews X cumsum([V(view(X, :, i)) for i in indices(X, 2)])

```

On my system, this is as fast as the @gideonsimpson’s second version, while using the  
`X`-matrix of the first version.
