Bonjour, je programme en C pour faire du calcul scientifique (résolution d'équations). Je suis donc très intéressé par tout ce qui touche la minimisation de la mémoire utilisée et la minimisation des temps de calculs.
Pour implémenter mes matrices, j'ai testé (après que Médinoc m'en ait parlé)
les deux méthodes de la FAQ (http://c.developpez.com/faq/?page=ta...bleau_2D_alloc)
L'intérêt de la 2nde méthode est qu'il n'y a que 2 malloc alors que sinon il y en a NR+1 mais l'inconvénient c'est que le second malloc est de très grande taille ce qui fait qu'il peut échouer plus facilement.
Donc que vaut-il faire ? 2 gros mallocs ou plein de petit malloc ?
Voici mon code pour la 2nde méthode
Lorsque je veux faire la somme de 2 matrices, je ne trouve pas de gain en temps... Y aurait-il donc une bonne raison pour que j'utilise le code ci-dessus ou bien vaut-il mieux que je reste à la méthode "traditionnelle" (c'est-à-dire la première dans la FAQ) ?
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 typedef struct { unsigned nr,nc; /* number of rows and columns */ double ** data; /* array containing all the values */ double * col; /* array containing all the values stored by columns */ } Matrix; Matrix * CreateMatrix(unsigned nr,unsigned nc,double d) { Matrix * mat=malloc(sizeof(*mat)); if(mat==NULL) { fprintf(stderr,"Error malloc()\n"); exit(1); } mat->nr=nr; mat->nc=nc; double ** prow=malloc(nr*sizeof(prow)); /* pointer to the rows of the matrix mat */ if(prow==NULL) { fprintf(stderr,"Error malloc()\n"); exit(1); } double * pcol=malloc(nr*nc*sizeof(*pcol)); /* pointer to the columns of the matrix mat */ if(pcol==NULL) { fprintf(stderr,"Error malloc()\n"); exit(1); } unsigned i,j; for(i=0;i<nr;++i) { prow[i]=&(pcol[i*nc]); for(j=0;j<nc;++j) prow[i][j]=d; } mat->data=prow; prow=NULL; mat->col=pcol; pcol=NULL; return mat; } void DestroyMatrix(Matrix ** m) { Matrix * mat=*m; free(mat->col); mat->col=NULL; free(mat->data); mat->data=NULL; mat->nr=mat->nc=0; mat=*m=NULL; } void PrintMatrix(Matrix * mat) { unsigned i,j,nr=mat->nr,nc=mat->nc; for(i=0;i<nr;++i) { for(j=0;j<nc;++j) printf("%f\t",mat->data[i][j]); printf("\n"); } }
J'espère avoir été clair...
Partager