Heapyなどの一般的なツールをいくつか調べて、各トラバーサル手法で使用されているメモリの量を測定しましたが、正しい結果が得られるかどうかはわかりません。コンテキストを提供するコードを次に示します。
このコードは、グラフ内の一意のノードの数を測定するだけです。2 つのトラバーサル手法が提供されました。count_bfs
とcount_dfs
import sys
from guppy import hpy
class Graph:
def __init__(self, key):
self.key = key #unique id for a vertex
self.connections = []
self.visited = False
def count_bfs(start):
parents = [start]
children = []
count = 0
while parents:
for ind in parents:
if not ind.visited:
count += 1
ind.visited = True
for child in ind.connections:
children.append(child)
parents = children
children = []
return count
def count_dfs(start):
if not start.visited:
start.visited = True
else:
return 0
n = 1
for connection in start.connections:
n += count_dfs(connection)
return n
def construct(file, s=1):
"""Constructs a Graph using the adjacency matrix given in the file
:param file: path to the file with the matrix
:param s: starting node key. Defaults to 1
:return start vertex of the graph
"""
d = {}
f = open(file,'rU')
size = int(f.readline())
for x in xrange(1,size+1):
d[x] = Graph(x)
start = d[s]
for i in xrange(0,size):
l = map(lambda x: int(x), f.readline().split())
node = l[0]
for child in l[1:]:
d[node].connections.append(d[child])
return start
if __name__ == "__main__":
s = construct(sys.argv[1])
#h = hpy()
print(count_bfs(s))
#print h.heap()
s = construct(sys.argv[1])
#h = hpy()
print(count_dfs(s))
#print h.heap()
2つのトラバーサル手法で合計メモリ使用率がどのような要因で異なるのかを知りたい. count_dfs
そしてcount_bfs
?dfs
関数呼び出しごとに新しいスタックが作成されるため、費用がかかる可能性があるという直観があるかもしれません。各トラバーサル手法でのメモリ割り当ての合計はどのように測定できますか?
(コメントされた)hpy
ステートメントは、望ましい尺度を示していますか?
接続を含むサンプル ファイル:
4
1 2 3
2 1 3
3 4
4