1 /* 2 * Copyright 2008, Ingo Weinhold, ingo_weinhold@gmx.de. 3 * Distributed under the terms of the MIT License. 4 */ 5 6 #include <limits.h> 7 #include <stdint.h> 8 #include <stdio.h> 9 #include <stdlib.h> 10 #include <unistd.h> 11 12 13 #ifndef PAGE_SIZE 14 # define PAGE_SIZE 4096 15 #endif 16 17 #define PAGE_ELEMENT_COUNT (PAGE_SIZE / 4) 18 19 20 int 21 main(int argc, const char* const* argv) 22 { 23 size_t allocationSize = 256; 24 25 if (argc > 1) { 26 allocationSize = atoi(argv[1]); 27 if (allocationSize == 0) { 28 fprintf(stderr, "Usage: %s [ <size in MB> ]\n", argv[0]); 29 return 1; 30 } 31 } 32 33 allocationSize *= 1024 * 1024; 34 size_t elementCount = allocationSize / 4; 35 size_t pageCount = elementCount / PAGE_ELEMENT_COUNT; 36 37 // allocate memory 38 uint32_t* allocation = (uint32_t*)malloc(allocationSize); 39 if (allocation == NULL) { 40 fprintf(stderr, "Allocation failed!\n"); 41 return 1; 42 } 43 44 printf("Allocated %lu MB at %p. Filling the allocation...\n", 45 (unsigned long)allocationSize / 1024 / 1024, allocation); 46 47 // fill the pages 48 for (size_t i = 0; i < elementCount; i++) { 49 allocation[i] = i; 50 if ((i + 1) % (PAGE_ELEMENT_COUNT * 32) == 0) { 51 printf("\rfilled %9lu/%9lu pages", 52 (unsigned long)(i + 1) / PAGE_ELEMENT_COUNT, 53 (unsigned long)pageCount); 54 fflush(stdout); 55 } 56 } 57 58 printf("\rDone filling the allocation. Starting test iterations...\n"); 59 60 for (int testIteration = 0; testIteration < 5; testIteration++) { 61 sleep(1); 62 63 printf("Test iteration %d...\n", testIteration); 64 65 // test the pages 66 for (size_t i = 0; i < elementCount; i++) { 67 if (allocation[i] != i) { 68 printf(" incorrect value in page %lu\n", 69 (unsigned long)i / PAGE_ELEMENT_COUNT); 70 71 // skip the rest of the page 72 i = i / PAGE_ELEMENT_COUNT * PAGE_ELEMENT_COUNT 73 + PAGE_ELEMENT_COUNT - 1; 74 } else if ((i + 1) % PAGE_ELEMENT_COUNT == 0) { 75 // printf(" page %lu ok\n", 76 // (unsigned long)i / PAGE_ELEMENT_COUNT); 77 } 78 } 79 } 80 81 return 0; 82 } 83