/* 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>
#ifdef NOVLA
#include <malloc.h>
#endif

#define DATA_SIZE 32

struct data
{
    char something[DATA_SIZE];
};

static void test1(int n)
{
#ifndef NOVLA
    struct data *p[n];
#else
    struct data **p = _alloca(n * sizeof(struct data *));
#endif
    int i;
#ifdef ANALYZE
    int alloc = 0, allocsiz = 0, dealloc = 0, mov = 0, movsiz = 0;
#endif
    for(i = 0; i < n; i++)
    {
        p[i] = (struct data *)malloc(sizeof(struct data));
#ifdef ANALYZE
        alloc += 1;
        allocsiz += sizeof(struct data);
#endif
    }
    for(i = 0; i < n; i++)
    {
        free(p[i]);
#ifdef ANALYZE
        dealloc += 1;
#endif
    }
#ifdef ANALYZE
    printf("alloc = %d allocsiz = %d dealloc = %d mov = %d movsiz = %d\n", alloc, allocsiz, dealloc, mov, movsiz);
#endif
}

static void test2(int n)
{
    struct data *p, *p2;
    int siz;
#ifdef ANALYZE
    int alloc = 0, allocsiz = 0, dealloc = 0, mov = 0, movsiz = 0;
#endif
    siz = 1;
    p = (struct data *)malloc(siz * sizeof(struct data));
#ifdef ANALYZE
    alloc += 1;
    allocsiz += siz;
#endif
    while(siz < n)
    {
        siz = 2 * siz;
        p2 = (struct data *)malloc(siz * sizeof(struct data));
        memcpy(p2, p, siz / 2 * sizeof(struct data));
        free(p);
        p = p2;
#ifdef ANALYZE
    alloc += 1;
    allocsiz += (siz * sizeof(struct data));
    dealloc += 1;
    mov += 1;
    movsiz += (siz / 2 * sizeof(struct data));
#endif
    }
    free(p);
#ifdef ANALYZE
    dealloc += 1;
    printf("alloc = %d allocsiz = %d dealloc = %d mov = %d movsiz = %d\n", alloc, allocsiz, dealloc, mov, movsiz);
#endif
}

#ifndef ANALYZE
#define REP 10000

typedef void (*fptr)(int n);

static void measure(fptr f, int n)
{
    time_t t1, t2;
    int i;
    t1 = time(NULL);
    for(i = 0; i < REP; i++)
    {
        f(n);
    }
    t2 = time(NULL);
    printf("%d seconds\n", (int)(t2 - t1));
}
#endif

#define N 100000

int main()
{
#ifndef ANALYZE
    printf("Classic tree with %d nodes (repeated %d times):\n", N, REP);
    measure(test1, N);
    printf("Linear space copied with %d nodes (repeated %d times):\n", N, REP);
    measure(test2, N);
#else
    printf("Classic tree with %d nodes:\n", N);
    test1(N);
    printf("Linear space copied with %d nodes:\n", N);
    test2(N);
#endif
    return 0;
}
