如何在python中优化以下算法的内存和时间使用

R.B*_*ahl 2 python memory sorting performance networkx

我试图在Python中完成以下逻辑操作,但进入内存和时间问题.既然,我是python的新手,那么如何以及在哪里优化问题的指导将不胜感激!(我明白以下问题有点抽象)

import networkx as nx 
    dic_score = {}
    G = nx.watts_strogatz_graph(10000,10,.01) # Generate 2 graphs with 10,000 nodes using Networkx
    H = nx.watts_strogatz_graph(10000,10,.01)
    for Gnodes in G.nodes()
        for Hnodes in H.nodes ()  # i.e. For all the pair of nodes in both the graphs
           score = SomeOperation on (Gnodes,Hnodes)  # Calculate a metric 
           dic_score.setdefault(Gnodes,[]).append([Hnodes, score, -1 ]) # Store the metric in the form a Key: value, where value become a list of lists, pair in a dictionary
Run Code Online (Sandbox Code Playgroud)

然后根据此处提到的条件sorted_criterion对生成的字典中的列表进行排序

我的问题/疑问是:

1)有没有比使用for循环进行迭代更好的方法?

2)什么应该是最优化(最快)的方法来解决上述问题?我应该考虑使用其他数据结构而不是字典吗?或者可能是文件操作?

3)因为我需要对这个字典中的列表进行排序,这个列表有10,000个键,每个键对应一个10,000个值的列表,内存需求变得非常快,我用完了.

3)有没有办法将排序过程集成到字典本身的计算中,即避免单独循环进行排序?

任何输入将不胜感激!谢谢 !

cul*_*rón 5

1)您可以使用itertools模块中的一个功能.我只想提一下,你可以阅读手册或致电:

from itertools import product
help(product)
Run Code Online (Sandbox Code Playgroud)

这是一个例子:

for item1, item2 in product(list1, list2):
    pass
Run Code Online (Sandbox Code Playgroud)

2)如果结果太大而无法放入内存,请尝试将它们保存在某处.您可以将其输出到CSV文件中,例如:

with open('result.csv') as outfile:
   writer = csv.writer(outfile, dialect='excel')
   for ...
       writer.write(...)
Run Code Online (Sandbox Code Playgroud)

这将释放你的记忆.

3)我认为最好对事后的结果数据进行排序(因为sort功能相当快),而不是使问题复杂化并在运行中对数据进行排序.

您可以改为使用NumPy arroy/matrix操作(求和,产品,甚至将函数映射到每个矩阵行).这些速度非常快,有时过滤数据的成本高于计算所有内容.

如果您的应用程序仍然非常慢,请尝试对其进行分析,以确切了解哪些操作很慢或执行过多次:

from cProfile import Profile
p = Profile()

p.runctx('my_function(args)', {'my_function': my_function, 'args': my_data}, {})
p.print_stats()
Run Code Online (Sandbox Code Playgroud)

你会看到表格:

      2706 function calls (2004 primitive calls) in 4.504 CPU seconds

Ordered by: standard name

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     2    0.006    0.003    0.953    0.477 pobject.py:75(save_objects)
  43/3    0.533    0.012    0.749    0.250 pobject.py:99(evaluate)
...
Run Code Online (Sandbox Code Playgroud)