Skip to content
Extraits de code Groupes Projets
Valider 915c7502 rédigé par Christophe-Leblanc's avatar Christophe-Leblanc
Parcourir les fichiers

performance test for python

parent 2ffa3e4e
Aucune branche associée trouvée
Aucune étiquette associée trouvée
Aucune requête de fusion associée trouvée
Pipeline #30484 annulé
Fichier ajouté
graph {
0 [label=0]
2 [label=2]
0 -- 2 [label=4 dir=forward]
0 [label=0]
4 [label=4]
0 -- 4 [label=7 dir=forward]
0 [label=0]
1 [label=1]
0 -- 1 [label=4 dir=forward]
2 [label=2]
0 [label=0]
2 -- 0 [label=3 dir=forward]
1 [label=1]
0 [label=0]
1 -- 0 [label=9 dir=forward]
1 [label=1]
4 [label=4]
1 -- 4 [label=7 dir=forward]
1 [label=1]
3 [label=3]
1 -- 3 [label=10 dir=forward]
1 [label=1]
2 [label=2]
1 -- 2 [label=2 dir=forward]
4 [label=4]
0 [label=0]
4 -- 0 [label=9 dir=forward]
3 [label=3]
2 [label=2]
3 -- 2 [label=5 dir=forward]
}
Fichier ajouté
#include <stdint.h>
#define NB_NODES 5
#define NB_LINKS 10
int32_t LINKS[NB_LINKS][3] = {
{0, 1, 3},
{0, 2, 2},
{1, 2, 1},
{1, 3, -2},
{2, 3, 4},
{2, 4, 1},
{3, 4, 2},
{0, 3, 1},
{1, 4, 2},
{2, 0, -1}
};
graph.png

33,6 ko

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()
\ No newline at end of file
Impossible d'afficher diff de source : il est trop volumineux. Options pour résoudre ce problème : voir le blob.
Aucun aperçu pour ce type de fichier
Number of iterations, Number of nodes, Links size, Source node, Minimum cost, Maximum cost, Time for BF, Time for SPFA_SLF
10000 5 10 0 -4 4 0.00003108
10000 5 10 0 -4 4 0.00001678
10000 5 10 0 -4 4 0.00001427
10000 5 10 0 -4 4 0.00001363
10000 25 50 0 -10 10 0.00030640
10000 25 50 0 -10 10 0.00026869
10000 25 50 0 -10 10 0.00029570
10000 25 50 0 -10 10 0.00028216
10000 25 50 0 -10 10 0.00027970
10000 25 50 0 -10 10 0.00035282
10000 25 50 0 -10 10 0.00030537
10000 25 50 0 -10 10 0.00027629
1000 50 350 0 -25 25 0.00518876
1000 50 350 0 -25 25 0.00490556
1000 50 350 0 -25 25 0.00489480
1000 50 350 0 -25 25 0.00485835
100 750 1200 0 -50 50 0.23045785
100 750 1200 0 -50 50 0.20430856
100 750 1200 0 -50 50 0.19876927
10 2500 50000 0 -1500 1500 43.78349648
#Plus de négatif que de positif
1000 50 120 0 -50 5 0.00147268
1000 50 120 0 -50 5 0.00153322
1000 50 120 0 -50 5 0.00162718
1000 50 120 0 -50 5 0.00163333
1000 50 350 0 -50 5 0.00529458
1000 50 350 0 -50 5 0.00524702
1000 50 350 0 -50 5 0.00482742
1000 50 350 0 -50 5 0.00497017
200 350 2000 0 -500 5 0.21386693
200 350 2000 0 -500 5 0.21833981
#Plus de négatif que de positif
200 350 2000 0 -50 150 0.19522310
200 350 2000 0 -50 150 0.20343573
......@@ -2,17 +2,31 @@ import math
import argparse
import sys
def get_file_infos(data):
# # Données de graph.h directement intégrées dans le code
# NB_NODES = 5
# NB_LINKS = 7
# LINKS = [
# [2,0,1],
# [0,1,2],
# [0,3,3],
# [0,4,1],
# [1,2,-1],
# [3,1,-2],
# [3,4,5]
# ]
def get_file_infos(links):
"""
Récupère les informations basiques du graphe : le nombre de noeuds et de liens.
"""
nb_nodes = int.from_bytes(data[0:4], "big", signed=True)
nb_edges = int.from_bytes(data[4:], "big", signed=True)
nb_nodes = max(max(link[:2]) for link in links) + 1
nb_edges = len(links)
return nb_nodes, nb_edges
def bellman_ford(links, s, verbose):
def bellman_ford(links, s, nb_nodes, verbose):
"""
Exécute l'algorithme de Bellman-Ford avec comme noeud source `s`.
Retourne un tableau de distances pour atteindre chaque noeud depuis `s`,
......@@ -78,33 +92,16 @@ def get_max(dist, s):
return max_cost, max_node
def read_graph(filename):
def read_graph():
"""
Récupère le graphe représenté dans le fichier donné en argument.
Suit le format défini dans l'énoncé.
Récupère le graphe directement à partir des données définies dans le code.
"""
with open(filename, "rb") as fd:
binary_data = fd.read()
nb_nodes, nb_edges = get_file_infos(binary_data[:8])
if verbose:
print("Nombre de noeuds :", nb_nodes,
", nombre de liens :", nb_edges)
global LINKS, NB_NODES
nb_nodes, nb_edges = get_file_infos(LINKS)
return LINKS, nb_nodes
binary_data = binary_data[8:]
links = []
for i in range(nb_edges):
from_node = int.from_bytes(
binary_data[i * 12:i * 12 + 4], "big", signed=True)
to_node = int.from_bytes(
binary_data[i * 12 + 4:i * 12 + 8], "big", signed=True)
cost = int.from_bytes(
binary_data[i * 12 + 8:i * 12 + 12], "big", signed=True)
l1 = [from_node, to_node, cost]
links.append(l1)
return links, nb_nodes
if __name__ == "__main__":
......@@ -128,7 +125,7 @@ if __name__ == "__main__":
# Exemple de message que vous pouvez ecrire si le mode verbose est actif.
print(args, file=sys.stderr)
graph, nb_nodes = read_graph(args.input_file)
graph, nb_nodes = read_graph()
if output_fd == sys.stdout or output_fd == sys.stderr:
print("Nombre de noeuds: " + str(nb_nodes))
else:
......@@ -140,21 +137,9 @@ if __name__ == "__main__":
# Ces messages ne sont pas des messages de debug.
# Ils peuvent donc etre affiches (uniquement si la sortie choisie est stdout ou stderr)
# meme si le mode verbose n'est pas actif.
if output_fd == sys.stdout or output_fd == sys.stderr:
print("source : " + str(source))
print("Distances: ", dist)
d, n = get_max(dist, source)
print("\tdestination : " + str(n))
print("\tcout : " + str(d))
p = get_path(n, path, source)
print("\tnombre de noeuds : " + str(len(p)))
print("\tchemin : " + " ".join(str(x) for x in p))
else:
output_fd.write(source.to_bytes(4, "big"))
d, n = get_max(dist, source)
output_fd.write(n.to_bytes(4, "big"))
output_fd.write(d.to_bytes(8, "big", signed=True))
r = get_path(n, path, source)
output_fd.write(len(r).to_bytes(4, "big", signed=True))
for j in range(len(r)):
output_fd.write(r[j].to_bytes(4, "big"))
for source in range(1):
dist, path = bellman_ford(graph, source, verbose)
for i in range(nb_nodes):
print(f"Distance to node {i} : {dist[i]}")
print(f"Path to node {i} : {path[i]}")
0% Chargement en cours ou .
You are about to add 0 people to the discussion. Proceed with caution.
Terminez d'abord l'édition de ce message.
Veuillez vous inscrire ou vous pour commenter