/******************************************************************************
 ** LiDIA's Temporary Variable Manager
 ** Original Author: Ralf Dentzer
 ** Rewritten By: Thomas Papanikolaou
 ** Copyright (c) by the LiDIA Group
 ** All rights reserved
 *****************************************************************************/

/**
 ** We test allocating a number of variables of different size and then
 ** release them at once. MM is at least as fast as malloc/free.
 **/

#include "mm.h"
#include <stdlib.h>

typedef char   *char_ptr;
char_ptr       *table;
long           *len;

void 
mm_random_alloc_test(max)
	long            max;
{
	long            t;
	int             i;

	fprintf(stderr, "\ndoing %8ld allocs/dels using %22s in",
		max, "malloc/free");
	t = clock();
	t = clock();
	for (i = 0; i < max; i++)
		table[i] = (char *) malloc(len[i]);
	for (i = 0; i < max; i++)
		free((char *) table[i]);
	t = clock() - t;
	fprintf(stderr, " %ld ns", t);
}

void 
mm_random_mm_alloc_test(max)
	long            max;
{
	long            t;
	int             i;

	fprintf(stderr, "\ndoing %8ld allocs/dels using %22s in",
		max, "mm_malloc/mm_free");
	t = clock();
	t = clock();
	for (i = 0; i < max; i++)
		table[i] = (char *) mm_malloc(len[i]);
	for (i = 0; i < max; i++)
		mm_free(table[i]);
	/*
	 * for (i = 0; i < max; i++) mm_free_with_size(table[i], len[i]);
	 */
	t = clock() - t;
	fprintf(stderr, " %ld ns", t);
}

int 
main(argc, argv)
	int             argc;
	char           *argv[];
{
	long            l;
	long            i;
	if (argc == 2)
		l = atol(argv[1]);
	else
		l = 5000;

	table = (char_ptr *) malloc(l * sizeof(char_ptr));
	len = (long *) malloc(l * sizeof(long));
	for (i = 0; i < l; i++)
		len[i] = abs(random()) & 0xff;
	mm_random_alloc_test(l);
	mm_random_mm_alloc_test(l);
	mm_statistics();
	mm_collect();
	mm_statistics();
	fprintf(stderr, "\n");
	return 0;
}
