Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import time
from sp import bellman_ford
def main():
# Read graph and global information from text file
n, nb_nodes, links_size, s, min_cost, max_cost, graphs = read_graphs_from_file("random_graphs.txt")
execution_time = run_random_test(n, nb_nodes, links_size, s, graphs)
print(f"Do you want to add the test results to a text file? (y/n) ", end='')
user_input = input().strip().lower()
if user_input == 'y':
write_to_file(n, nb_nodes, links_size, s, min_cost, max_cost, execution_time)
print("The results have been added to the 'results.txt' file.")
def write_to_file(n, nb_nodes, links_size, s, min_cost, max_cost, execution_time):
file_name = "results.txt"
try:
file_exists = False
with open(file_name, 'r'):
file_exists = True
except FileNotFoundError:
pass
with open(file_name, 'a') as file:
if not file_exists:
file.write("Number of iterations, Number of nodes, Links size, Source node, Minimum cost, Maximum cost, Time for BF, Time for SPFA_SLF\n")
file.write(f"{n} {nb_nodes} {links_size} {s} {min_cost} {max_cost} {execution_time:.8f}\n")
def read_graphs_from_file(file_path):
graphs = []
with open(file_path, 'r') as file:
lines = file.readlines()
# Read the global information from the first line
n, nb_nodes, links_size, s, min_cost, max_cost = map(int, lines[0].strip().split(' '))
# Initialize an empty graph
graph = []
for line in lines[1:]:
line = line.strip()
if line == "=====":
# End of the current graph, append it to the list of graphs and start a new one
graphs.append(graph)
graph = []
else:
# Read the edge information and add it to the current graph
edge = list(map(int, line.split(' ')))
graph.append(edge)
return n, nb_nodes, links_size, s, min_cost, max_cost, graphs
def run_random_test(n, nb_nodes, links_size, s, graphs):
total_time = 0
for graph in graphs:
start_time = time.perf_counter()
bellman_ford(graph, s, nb_nodes, False)
end_time = time.perf_counter()
total_time += end_time - start_time
execution_time = total_time / n
print(f"Average execution time: {execution_time:.8f} seconds")
return execution_time
if __name__ == "__main__":
main()