我想将(x,y)坐标保存在不同个体访问的网格网络中。假设我有 1000 个人,网络大小为 x = 1:100
和 y=1:100
。我正在使用 Dict()
,这里是关于我想要执行的操作的示例代码:
individuals = 1:1000
x = 1:100
y = 1:100
function Visited_nodes()
nodes_of_inds =Dict{Int64, Array{Tuple{Int64, Int64}}}()
for ind in individuals
dum_array = Array{Tuple{Int64, Int64}}(0)
for i in x
for j in y
if rand()<0.2 # some conditions
push!(dum_array, (i,j))
end
end
end
nodes_of_inds[ind]=unique(dum_array)
end
return nodes_of_inds
end
@time nodes_of_inds = Visited_nodes()
# result: 1.742297 seconds (12.31 M allocations: 607.035 MB, 6.72% gc time)
但这效率不高。我很感激任何如何提高效率的建议。
最佳答案
请参阅performance tips 。第一条建议是:避免全局变量。 individuals
、x
和 y
都是非常量全局变量。让它们成为你的函数的参数。仅此更改就可以将您的功能加速一个数量级。
通过构造,您的 dum_array
中不会有任何重复的元组,因此您不需要调用 unique
。这又减少了两倍。
最后,Array{T}
不是 a concrete type 。 Julia 的数组还将维度编码为类型参数,必须包含该参数才能使数组字典高效。请改用 Array{T, 1}
或 Vector{T}
。不过,这并不是此函数运行期间的主要考虑因素。
剩下的主要问题就是O(length(individuals)*length(x)*length(y))
计算复杂度。做任何事情一千万次都会很快加起来,无论效率有多高。
关于arrays - 在 julia 中高效构建数组字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43577727/