Construire le rapport en temps linéaire

ajouter() recalculait la longueur du rapport à chaque ligne : 5 867
parcours d'une chaîne qui grandit jusqu'à ~90 Ko (O(n²) en caractères).
On garde un pointeur sur la fin du rapport et on écrit directement à la
suite avec sprintf.

gprof n'attribuait que 0,04 s à construire_rapport, car il répartit le
temps de longueur() au prorata du nombre d'appels : la mesure montre que
c'était en réalité le premier poste restant.

Temps : 2,0 s → 1,06 s. Empreinte inchangée (1d53de903efd2b7c).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-14 14:00:02 +02:00
parent 255a73982c
commit cd34f39535
+4 -8
View File
@@ -380,15 +380,11 @@ void analyser_bigrammes(char **lignes, int nb_lignes,
char *construire_rapport(const Entree *table, int n)
{
char *rapport = malloc((size_t)n * 64 + 256);
char ligne[128];
rapport[0] = '\0';
char *fin = rapport; /* position du '\0' final : on écrit directement à la suite */
ajouter(rapport, "rang;mot;occurrences\n");
for (int i = 0; i < n; i++) {
snprintf(ligne, sizeof(ligne), "%d;%s;%d\n",
i + 1, table[i].mot, table[i].occurrences);
ajouter(rapport, ligne);
}
fin += sprintf(fin, "rang;mot;occurrences\n");
for (int i = 0; i < n; i++)
fin += sprintf(fin, "%d;%s;%d\n", i + 1, table[i].mot, table[i].occurrences);
return rapport;
}