forked from oils-for-unix/oils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdumb_alloc.cc
88 lines (72 loc) · 2.05 KB
/
dumb_alloc.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// dumb_alloc.cc: Test this C++ mechanism as a lower bound on performance.
#include "dumb_alloc.h"
#include <stdio.h>
// 400 MiB of memory
char kMem[400 << 20];
int gMemPos = 0;
int gNumNew = 0;
int gNumDelete = 0;
// I'm not sure why this matters but we get crashes when aligning to 8 bytes.
// That is annoying.
// Example: we get a crash in cpp/frontend_flag_spec.cc
// auto out = new flag_spec::_FlagSpecAndMore();
//
// https://stackoverflow.com/questions/52531695/int128-alignment-segment-fault-with-gcc-o-sse-optimize
constexpr int kMask = alignof(max_align_t) - 1; // e.g. 15 or 7
// Align returned pointers to the worst case of 8 bytes (64-bit pointers)
inline size_t aligned(size_t n) {
// https://stackoverflow.com/questions/2022179/c-quick-calculation-of-next-multiple-of-4
// return (n + 7) & ~7;
return (n + kMask) & ~kMask;
}
// This global interface is silly ...
#ifdef DUMB_ALLOC
void* operator new(size_t size) {
char* p = &(kMem[gMemPos]);
#ifdef ALLOC_LOG
printf("new %zu\n", size);
#endif
gMemPos += aligned(size);
++gNumNew;
return p;
}
// noexcept fixes Clang warning
void operator delete(void* p) noexcept {
// fprintf(stderr, "\tdelete %p\n", p);
++gNumDelete;
}
#endif
char kMem2[400 << 20];
int gMemPos2 = 0;
int gNumMalloc = 0;
int gNumFree = 0;
#ifdef DUMB_ALLOC
void* dumb_malloc(size_t size) noexcept {
char* p = &(kMem2[gMemPos2]);
#ifdef ALLOC_LOG
printf("malloc %zu\n", size);
#endif
gMemPos2 += aligned(size);
++gNumMalloc;
return p;
}
void dumb_free(void* p) noexcept {
// fprintf(stderr, "free\n");
++gNumFree;
}
#endif
namespace dumb_alloc {
void Summarize() {
#ifdef DUMB_ALLOC
fprintf(stderr, "\n");
fprintf(stderr, "dumb_alloc:\n");
fprintf(stderr, "\tgNumNew = %d\n", gNumNew);
fprintf(stderr, "\tgNumDelete = %d\n", gNumDelete);
fprintf(stderr, "\tgMemPos = %d\n", gMemPos);
fprintf(stderr, "\n");
fprintf(stderr, "\tgNumMalloc = %d\n", gNumMalloc);
fprintf(stderr, "\tgNumFree = %d\n", gNumFree);
fprintf(stderr, "\tgMemPos2 = %d\n", gMemPos2);
#endif
}
} // namespace dumb_alloc