What is the fastest way to reset julia array for all zeros?

Suppose I have an existing array, for example

x = rand(4)

and then I want reset xto be zero. Can i avoid the execution x = zeros(4). I am interested in memory allocation.

+4
source share
3 answers

The best way to do this in one line:

x[:] = zero(y)

or

fill!(x,zero(y))

y - , , . , , , . x - , , y (, y=x[1]).

, , , SIUnits. , SIUnits , x ( ), fill!(x, 0.0) - ( fill!(x,zeros(y)). .

+8

fill!(x, 0.0)

.

, for:

for i in 1:length(x)
    x[i] = 0.0
end

, @edit fill!(x, 0.0), , , ( , @inbounds ).

+3

, , , " ( , )".

, . :

f1(x) = x    = zeros(size(x));
f2(x) = x[:] = zero(x[1]);
f3(x) = fill!(x, zero(x[1]));
f4(x) = x    = zero(x);

:

julia> x=rand(1000,1000); @time (for i in 1_000_000_000; x=f1(x); end;)
  0.000715 seconds (3 allocations: 7.629 MB)

julia> x=rand(1000,1000); @time (for i in 1_000_000_000; f2(x); end;)
  0.000691 seconds (2 allocations: 32 bytes)

julia> x=rand(1000,1000); @time (for i in 1_000_000_000; f3(x); end;)
  0.000702 seconds (2 allocations: 32 bytes)

julia> x=rand(1000,1000); @time (for i in 1_000_000_000; x=f4(x); end;)
  0.000704 seconds (2 allocations: 7.629 MB)


PS. , , , , , " , " ...
, f1 f4 ; , ; , , , -, OP.

, "" , , :)

+1

Source: https://habr.com/ru/post/1655059/


All Articles