/* Collection of code snippets by Arne Vajhøj */
/* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void check(char *b);

void run(int nobj, int objsiz)
{
    char **a;
    int i, j;
    a = malloc(nobj * sizeof(char *));
    for(i = 0; i < nobj; i++)
    {
        a[i] = malloc(objsiz);
    }
    for(i = 0; i < nobj; i++)
    {
        for(j = 0; j < objsiz; j++) a[i][j] = i + j;
        check(a[i]);
    }
    for(i = 0; i < nobj; i++)
    {
        free(a[i]);
    }
    free(a);
}

void test(int rep, int nobj, int objsiz, double dt)
{
    time_t t1, t2;
    int i;
    t1 = time(NULL);
    for(i = 0; i < rep; i++)
    {
        run(nobj, objsiz);
    }
    t2 = time(NULL);
    printf("%d objects of %d bytes : %.3f us per object (%.3f processing)\n", nobj, objsiz, (t2 - t1) * 1000000.0 / (rep * 1.0 * nobj) - dt, dt);
}

double nomem(int rep, int nobj, int objsiz)
{
    time_t t1, t2;
    char **a;
    int i, j, k;
    a = malloc(nobj * sizeof(char *));
    for(i = 0; i < nobj; i++)
    {
        a[i] = malloc(objsiz);
    }
    t1 = time(NULL);
    for(k = 0; k < rep; k++)
    {
        for(i = 0; i < nobj; i++)
        {
            for(j = 0; j < objsiz; j++) a[i][j] = i + j;
            check(a[i]);
        }
    }
    t2 = time(NULL);
    for(i = 0; i < nobj; i++)
    {
        free(a[i]);
    }
    free(a);
    return (t2 - t1) * 1000000.0 / (rep * 1.0 * nobj);
}

#define REP 1000

int main()
{
    double dt;
    int i, j;
    for(i = 1; i <= 4; i++)
    {
        for(j = 1; j <= 4; j++)
        {
            dt = nomem(REP, i * 1000000, j * 10);
            test(REP, i * 1000000, j * 10, dt);
        }
    }
    return 0;
}
