一个简单的例子,数组a中的每一个元素除以3,代码如下:
function foo_2(n)
a = collect(1:n)
for i = 1:size(a, 1)
a[i] = a[i]/3
end
end
julia > @benchmark foo_2(100000000.0)
BenchmarkTools.Trial:
memory estimate: 762.94 MiB
allocs estimate: 2
--------------
minimum time: 1.264 s (0.90% GC)
median time: 1.399 s (8.76% GC)
mean time: 1.376 s (7.50% GC)
maximum time: 1.444 s (10.73% GC)
--------------
samples: 4
evals/sample: 1
我将它改成并行的例子后:
using SharedArrays
using Distributed
addprocs(2)
function foo_1(n)
a = collect(1:n)
a = SharedArray(a)
@sync @distributed for i = 1:size(a, 1)
a[i] = a[i]/3
end
end
julia > @benchmark foo_1(100000000.0)
BenchmarkTools.Trial:
memory estimate: 762.97 MiB
allocs estimate: 809
--------------
minimum time: 10.795 s (0.10% GC)
median time: 10.795 s (0.10% GC)
mean time: 10.795 s (0.10% GC)
maximum time: 10.795 s (0.10% GC)
--------------
samples: 1
evals/sample: 1