standalone_malloc_test.cc revision 09575a176caef64cf43f3eac8e197ee4f55572bd
1#include <stdio.h> 2#include <vector> 3#include <pthread.h> 4#include <malloc.h> 5#include <algorithm> 6 7using namespace std; 8 9const size_t kNumThreds = 16; 10const size_t kNumIters = 1 << 23; 11 12static void *MallocThread(void *t) { 13 size_t total_malloced = 0, total_freed = 0; 14 size_t max_in_use = 0; 15 size_t tid = reinterpret_cast<size_t>(t); 16 vector<pair<char *, size_t> > allocated; 17 allocated.reserve(kNumIters); 18 for (size_t i = 1; i < kNumIters; i++) { 19 if ((i % (kNumIters / 4)) == 0 && tid == 0) 20 fprintf(stderr, " T[%ld] iter %ld\n", tid, i); 21 bool allocate = (i % 5) <= 2; // 60% malloc, 40% free 22 if (i > kNumIters / 4) 23 allocate = i % 2; // then switch to 50% malloc, 50% free 24 if (allocate) { 25 size_t size = 1 + (i % 200); 26 if ((i % 10001) == 0) 27 size *= 4096; 28 total_malloced += size; 29 char *x = new char[size]; 30 x[0] = x[size - 1] = x[size / 2] = 0; 31 allocated.push_back(make_pair(x, size)); 32 max_in_use = max(max_in_use, total_malloced - total_freed); 33 } else { 34 if (allocated.empty()) continue; 35 size_t slot = i % allocated.size(); 36 char *p = allocated[slot].first; 37 p[0] = 0; // emulate last user touch of the block 38 size_t size = allocated[slot].second; 39 total_freed += size; 40 swap(allocated[slot], allocated.back()); 41 allocated.pop_back(); 42 delete [] p; 43 } 44 } 45 if (tid == 0) 46 fprintf(stderr, " T[%ld] total_malloced: %ldM in use %ldM max %ldM\n", 47 tid, total_malloced >> 20, (total_malloced - total_freed) >> 20, 48 max_in_use >> 20); 49 for (size_t i = 0; i < allocated.size(); i++) 50 delete [] allocated[i].first; 51 return 0; 52} 53 54// Build with -Dstandalone_malloc_test=main to make it a separate program. 55int standalone_malloc_test() { 56 pthread_t t[kNumThreds]; 57 for (size_t i = 0; i < kNumThreds; i++) 58 pthread_create(&t[i], 0, MallocThread, reinterpret_cast<void *>(i)); 59 for (size_t i = 0; i < kNumThreds; i++) 60 pthread_join(t[i], 0); 61 malloc_stats(); 62 return 0; 63} 64