standalone_malloc_test.cc revision 0b9218ab2b68401673c5d6225c9833bd58003ed4
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 << 20;
11
12
13static void *MallocThread(void *t) {
14  size_t total_malloced = 0, total_freed = 0;
15  size_t max_in_use = 0;
16  size_t tid = reinterpret_cast<size_t>(t);
17  vector<pair<char *, size_t> > allocated;
18  allocated.reserve(kNumIters);
19  for (size_t i = 1; i < kNumIters; i++) {
20    if ((i % (kNumIters / 2)) == 0 && tid == 0)
21      fprintf(stderr, "   T[%ld] iter %ld\n", tid, i);
22    if ((i % 5) <= 2) {  // 0, 1, 2
23      size_t size = 1 + (i % 200);
24      if ((i % 10001) == 0)
25        size *= 4096;
26      total_malloced += size;
27      char *x = new char[size];
28      x[0] = x[size - 1] = x[size / 2] = 0;
29      allocated.push_back(make_pair(x, size));
30      max_in_use = max(max_in_use, total_malloced - total_freed);
31    } else {  // 3, 4
32      if (allocated.empty()) continue;
33      size_t slot = i % allocated.size();
34      char *p = allocated[slot].first;
35      size_t size = allocated[slot].second;
36      total_freed += size;
37      swap(allocated[slot], allocated.back());
38      allocated.pop_back();
39      delete [] p;
40    }
41  }
42  if (tid == 0)
43    fprintf(stderr, "   T[%ld] total_malloced: %ldM in use %ldM max %ldM\n",
44           tid, total_malloced >> 20, (total_malloced - total_freed) >> 20,
45           max_in_use >> 20);
46  for (size_t i = 0; i < allocated.size(); i++)
47    delete [] allocated[i].first;
48  return 0;
49}
50
51// Build with -Dstandalone_malloc_test=main to make it a separate program.
52int standalone_malloc_test() {
53  pthread_t t[kNumThreds];
54  for (size_t i = 0; i < kNumThreds; i++)
55    pthread_create(&t[i], 0, MallocThread, reinterpret_cast<void *>(i));
56  for (size_t i = 0; i < kNumThreds; i++)
57    pthread_join(t[i], 0);
58  malloc_stats();
59  return 0;
60}
61