2015-10-14 127 views
0

我有以下代碼,它獲取要排除的圖和一組ID,並返回未出現在要排除的節點列表中的節點的ID。這條線爲什麼需要這麼長時間才能運行?

我有兩個版本的代碼。一個獲得兩個列表,另一個獲得一個列表。我正在使用itertools.chain來組合這兩個列表。

from itertools import chain 

def GrapMinusNodes(Graph,nodes_to_exclude1,nodes_to_exclude2): 
    return (item.GetId() for item in Graph.Nodes() if item.GetId() not in chain(nodes_to_exclude1,nodes_to_exclude2)) 

和我有這樣一個:

def GrapMinusNodes(Graph,nodes_to_exclude1,nodes_to_exclude2): 
    return (item.GetId() for item in Graph.Nodes() if item.GetId() not in nodes_to_exclude1) 

第一種方法的運行速度比所述第二個較慢的20%。 這是什麼原因? 有沒有辦法讓這段代碼運行得更快?

+1

這是因爲你在'Graph.Nodes()創建每個項目的''chain'在第一種方法 – inspectorG4dget

+3

那麼,你必須創建鏈對象,並創建它具有非零成本。你到底在期待什麼?同時處理更多處理器指令? –

+0

在循環之外創建'chain'對象:) –

回答

2

你爲什麼在這裏使用chain?爲迭代檢查成員資格是O(n),並且您必須重新創建您要檢查的每個項目的迭代。相反,使用預創建set和測試成員:

exclude = set().union(nodes_to_exclude1, nodes_to_exclude2) 
return (item.GetId() for item in Graph.Nodes() if item.GetId() not in exclude) 
相關問題