add info on memory allocation and recursition depth
authorLaurent MAZET <laurent.mazet@thalesgroup.com>
Thu, 23 Oct 2025 09:03:17 +0000 (11:03 +0200)
committerLaurent MAZET <laurent.mazet@thalesgroup.com>
Thu, 23 Oct 2025 09:03:17 +0000 (11:03 +0200)
load.c

diff --git a/load.c b/load.c
index 45541221abcae877d453eabd9ef5bf305ef17c19..852c5a2953779d0bdd224fcc9d23b46b820161a8 100644 (file)
--- a/load.c
+++ b/load.c
@@ -52,22 +52,43 @@ int usage (int ret)
     return ret;
 }
 
+/* monitor allocation */
+
+int max_alloc = 0;
+int cur_alloc = 0;
+
+void *my_calloc (size_t nmemb, size_t size)
+{
+    // cur_alloc += nmemb * size;
+    __sync_fetch_and_add (&cur_alloc, nmemb * size);
+    if (max_alloc < cur_alloc) max_alloc = cur_alloc;
+    return calloc (nmemb, size);
+}
+
+void my_free (void *ptr, size_t size)
+{
+    // if (ptr) cur_alloc -= size;
+    if (ptr) __sync_fetch_and_sub (&cur_alloc, size);
+    free (ptr);
+}
+
 /* matix functions */
 
 matrix_t * alloc_matrix (int n)
 {
-    matrix_t *m = (matrix_t *) calloc (1, sizeof (matrix_t));
+    matrix_t *m = (matrix_t *) my_calloc (1, sizeof (matrix_t));
     assert (m);
+
     m->n = n;
-    m->mat = (double *) calloc (n * n, sizeof (double));
+    m->mat = (double *) my_calloc (n * n, sizeof (double));
     assert (m->mat);
     return m;
 }
 
 void free_matrix (matrix_t *m)
 {
-    if (m) free (m->mat);
-    free (m);
+    if (m) my_free (m->mat, m->n * m->n * sizeof (double));
+    my_free (m, sizeof (matrix_t));
 }
 
 int set_matrix (matrix_t *m, int i, int j, double val)
@@ -104,13 +125,21 @@ void get_comatrix (matrix_t *comatrix, matrix_t *matrix, int k, int l)
     }
 }
 
+int max_rec = 0;
+int cur_rec = 0;
+
 double determinant (matrix_t *matrix)
 {
+    // cur_rec++;
+    __sync_fetch_and_add (&cur_rec, 1);
+    if (max_rec < cur_rec) max_rec = cur_rec;
     double det = 0;
 
     if (matrix->n == 1) {
         double val;
         get_matrix (matrix, 0, 0, &val);
+        // cur_rec--;
+        __sync_fetch_and_sub (&cur_rec, 1);
         return val;
     }
 
@@ -125,6 +154,8 @@ double determinant (matrix_t *matrix)
     }
     free_matrix (comatrix);
 
+    // cur_rec--;
+    __sync_fetch_and_sub (&cur_rec, 1);
     return det;
 }
 
@@ -146,7 +177,7 @@ void *work (__attribute__((unused)) void *arg)
         matrix_t *matrix = alloc_matrix (N);
         generate_matrix (matrix);
         double det = determinant (matrix);
-        printf ("det: %g\n", det);
+        printf ("det: %g (max %dB used, max rec %d)\n", det, max_alloc, max_rec);
         free_matrix (matrix);
     }
     pthread_exit (NULL);