function test1(d::Int64, D::Int64, v::Vector{Float64})
L = d * D
A = zeros(eltype(v),(L, L))
count = 1
for j = 1:L
for i=1:L
if i > j
A[i,j] = v[count]
A[j,i] = -v[count]
count += 1
end
end
end
return A
end
但考虑到 Julia 以列为主的存储形式,for 循环中的 A[j,i] = -v[count] 跨越了不同的列,因而似乎这不是优化的实现?
加上 @inbounds 可以轻微提升(7.7->6.2μs),如果 L 不变 A 能重复利用,可以在外边创建,减少开销 (6.2->5.8)
const A = zeros(Float64, (100, 100)) # L = 100
function test1(v::AbstractVector, L::Int)
# A = zeros(Float64, (L, L))
count = 1
@inbounds for i = 1:L, j = 1:L
if i > j
A[i, j] = v[count]
A[j, i] = -v[count]
count += 1
end
end
return A
end
using BenchmarkTools
v = rand(4950)
@btime test1($v, 100);
function test2(d::Int64, D::Int64, v::Vector{Float64})
L = d * D
A = zeros(eltype(v),(L, L))
for i = 2:L
for j = 1:i-1
A[i,j] = -v[(i-2)*(i-1)/2+j]
end
end
return A-transpose(A)
end
A = Array{eltype(v)}(undef, L, L)
@inbounds for i in 1:L, j in 1:L
A[j, i] = if i > j
v[((i-1)*(i-2))>>1+j]
elseif i < j
-v[((j-1)*(j-2))>>1+i]
else
0
end
end