Skip to content
Extraits de code Groupes Projets
performance_tests.py 2,41 ko
Newer Older
  • Learn to ignore specific revisions
  • 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()