#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <sys/time.h>
#include <unistd.h>

struct timeval tv1;
struct timeval tv2;

void display_mem() {
    char buf[1024];
    char *ptr, *ptr2;
    ssize_t amount;
    int fd = open("/proc/self/status", O_RDONLY);
    if (fd == -1) {
        printf("cannot open file\n");
        return;
    }
     
    amount = read(fd, buf, 1023);
    buf[amount] = '\0';
    if (!(ptr = strstr(buf, "VmSize:"))) {
        printf("VmSize not found in: %s\n", buf);
        close(fd);
        return;
    }

    if (!(ptr2 = strchr(ptr, '\n'))) {
        printf("\\n not found\n");
        close(fd);
        return;
    }

    *(ptr2+1) = '\0';
    printf(ptr);
    close(fd);
}

#define count 20

int main(int argc, char** argv) {
        int i, j;
        void* pixbufs[count] = { NULL, };
        
        display_mem();
        printf("\n");

        i = 0;
	j = 0;

        gettimeofday(&tv1, NULL);

        while (1) {
                pixbufs[i] = malloc(16*1024*1024);
                if (!pixbufs[i]) {
                        fprintf(stderr, "failure with malloc\n");
                        abort();
                }
                bzero(pixbufs[i], 16*1024*1024);
                i++;
                if (i == count) {
                        gettimeofday(&tv2, NULL);
                        printf("alloc in %d ms\n", (int) (1000*(tv2.tv_sec - tv1.tv_sec) + ((double)tv2.tv_usec - tv1.tv_usec)/1000));

                        display_mem();

                        gettimeofday(&tv1, NULL);
                        for ( i = 0; i < count - 1; i++ )
                                free(pixbufs[i]);
                        gettimeofday(&tv2, NULL);
                        printf("free all but last in %d ms\n", (int) (1000*(tv2.tv_sec - tv1.tv_sec) + ((double)tv2.tv_usec - tv1.tv_usec)/1000));

                        display_mem();

                        /*
			if (system("touch foo") == -1) {
                        	fprintf(stderr, "system failed: %s\n", strerror(errno));
				abort();
                        }*/

                        j++;
                        if (j == 5) {
                                return 0;
                        }

                        // last one becomes first
			printf("\n");
                        pixbufs[0] = pixbufs[count - 1];
                        i = 1;

                        gettimeofday(&tv1, NULL);
                }
        }

        return 0;
}

