【问题标题】:Build Dictionary of Arrays Efficiently in julia在 julia 中有效地构建数组字典
【发布时间】:2017-04-23 23:44:54
【问题描述】:

我想将 (x,y) 坐标保存在不同个人访问的网格网络中。假设我有 1000 个人,网络规模为 x = 1:100y=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)

但这不是有效的。我感谢任何建议如何提高效率。

【问题讨论】:

    标签: arrays dictionary data-structures julia


    【解决方案1】:

    请参阅performance tips。那里的第一条建议:避免使用全局变量。 individualsxy 都是非常量全局变量。将它们作为您的函数的参数。仅此更改即可将您的功能加快一个数量级。

    通过构造,您的dum_array 中不会有任何重复的元组,因此您无需调用unique。这又减少了两倍。

    最后,Array{T} 不是a concrete type。 Julia 的数组还将维数编码为类型参数,必须包含它才能使数组字典有效。请改用Array{T, 1}Vector{T}。不过,在这个函数的时间内,这不是主要考虑因素。

    剩下的主要就是O(length(individuals)*length(x)*length(y)) 计算复杂度。做任何事情 1000 万次都会很快累积起来,无论效率如何。

    【讨论】:

      【解决方案2】:

      @Matt B.,感谢您的回复。关于全局变量,我尝试了代码的简化版本,但对性能没有帮助。 假设我从几个 csv 文件中读取了输入数据,并且我有三个具有不同参数的函数:

      function Read_input_data()
         # read input data
         individuals = readcsv("file1")
         x = readcsv("file2")
         y = readcsv("file3")
         A = readcsv("file4")
         B = readcsv("file5") # and a few other files
      
         # call different functions
         result_1 = Function1(individuals , x, y)
         result_2 = Function2(result_1 ,y, A, B)
         result_3 = Function3(result_2 , individuals, A, B)
         return result_1, result_2, result_3 
      end
      
      result_1, result_2, result_3 = Read_input_data()
      

      我不知道为什么与我定义所有全局时相比性能没有更好!如果您对此发表评论,我将不胜感激!

      【讨论】:

      • 如果没有更多关于 FunctionN 调用在做什么的上下文,就不可能说为什么这很慢。
      猜你喜欢
      • 2012-01-16
      • 1970-01-01
      • 2015-07-25
      • 2014-07-22
      • 2017-04-25
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 2017-06-16
      相关资源
      最近更新 更多