in-place array operations

145 views
Skip to first unread message

Deniz Yuret

unread,
Nov 30, 2014, 12:24:25 PM11/30/14
to julia...@googlegroups.com
I am trying to figure out the most efficient way to perform in-place array operations in Julia.

julia> a=rand(10000,10000)

julia
> tic(); b=sin(a); toc();
elapsed time
: 1.25738114 seconds

julia
> tic(); map!(sin,a); toc();
elapsed time
: 7.821650464 seconds

julia
> tic(); for i=1:length(a); a[i]=sin(a[i]); end; toc();
elapsed time
: 24.993171377 seconds

Nothing seems faster than creating a new array, which I'd like to avoid without slowing down the code if possible.

Any ideas?

John Myles White

unread,
Nov 30, 2014, 12:26:15 PM11/30/14
to julia...@googlegroups.com
Hi Deniz,

If you time things in the global scope, you will come to incorrect conclusions about performance. If you want to do performance comparisons, you need to do them inside of a function body to get meaningful results.

 — John

Deniz Yuret

unread,
Nov 30, 2014, 12:52:02 PM11/30/14
to julia...@googlegroups.com
Thanks John.  Here is the results when wrapped in a function body.  The for loop wins as expected, map! still looks horrible...

julia> a=rand(10000,10000)
julia
> f1(a::Array{Float64})=map!(sin,a)
julia
> @time f1(a);
elapsed time
: 7.344967598 seconds (4799991904 bytes allocated, 21.07% gc time)
julia
> function g1(a::Array{Float64}) b=sin(a); end
julia
> @time g1(a);
elapsed time
: 0.886401569 seconds (800000128 bytes allocated)
julia
> function h1(a::Array{Float64}) for i=1:length(a); a[i]=sin(a[i]); end; end
julia
> @time h1(a);
elapsed time
: 0.70801756 seconds (80 bytes allocated)

Ivar Nesje

unread,
Nov 30, 2014, 1:41:53 PM11/30/14
to julia...@googlegroups.com
map is horrible for small and fast functions like sin, because Julia currently doesn't generate specialized code, so method dispatch for both sin and the resulting setindex! call needs to be performed runtime (for every element of the array). There are open issues about fixing this.

Ivar
Reply all
Reply to author
Forward
0 new messages