/* gcc memtest.c -lrt */
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
int block_size = 256;
int array_size = 1024*1024;
void* thread (void *v)
{
long i;
int **array = malloc(array_size * sizeof(int*));
for(i = 0; i < array_size; i++){
int *s = malloc(block_size);
int j;
for(j = 0; j <block_size/sizeof(int); j++)
s[j] = j;
array[i] = s;
if(array_size >= 10 && !(i%(array_size/10))){
float percent = (float)i/array_size*100.0;
printf("\t thread %x: %f%%%% creation done\n", (unsigned)pthread_self(), percent);
}
}
for(i = 0; i < array_size; i++){
int *s = array[i];
int j;
for(j = 0; j <block_size/sizeof(int); j++)
if(s[j] != j)
printf("\t MEMERROR in thread #%x\n", (unsigned)pthread_self());
free(s);
if(array_size >= 10 && !(i%(array_size/10))){
float percent = (float)i/array_size*100.0;
printf("\t thread %x: %f%%%% deletion done\n", (unsigned)pthread_self(), percent);
}
}
printf("\tfinished thread #%x\n", (unsigned)pthread_self());
free(array);
return NULL;
}
int main (int argc, char** argv)
{
int thread_count = 5;
if(argc > 1)
block_size = atoi(argv[1]);
if(argc > 2)
array_size = atoi(argv[2]);
if(argc > 3)
thread_count = atoi(argv[3]);
printf("malloc performance tester\nUsage: %s [block_size] [array_size] [thread_count]\n", argv[0]);
printf("going to allocate array of blocks in each of the %d threads [block_size = %d,"
"array_size = %d] \n", thread_count, block_size, array_size);
pthread_t pids[thread_count];
memset(pids, 0, sizeof(pids));
int i;
for(i = 0; i < thread_count; i++)
if (-1 == pthread_create(pids + i, NULL, &thread, NULL)){
perror("creation of the thread failed");
exit(-1);
}
for(i = 0; i < thread_count; i++){
pthread_join(pids[i], NULL);
printf("joined thread #%x\n", (unsigned)pids[i]);
}
printf("finished main thread #%x\n", (unsigned)pthread_self());
return 0;
}