8#ifndef INCLUDED_SDSL_MEMORY_MANAGEMENT
9#define INCLUDED_SDSL_MEMORY_MANAGEMENT
27#include <system_error>
43 using namespace std::chrono;
46 <<
"\"" << ev.
name <<
"\",\n";
52 out <<
"\t\t\t[" << duration_cast<milliseconds>(ev.
allocations[j].timestamp - m.
start_log).count() <<
","
71 std::sort(events.begin(), events.end());
75 for (
size_t i = 0; i < events.size(); i++)
79 if (i < events.size() - 1)
93 std::stringstream jsonheader;
94 jsonheader <<
"<html>\n"
96 <<
"<meta charset=\"utf-8\">\n"
98 <<
" body { font: 11px sans-serif; }\n"
99 <<
" .rule { height: 90%; position: absolute; border-right: 1px dotted #000; "
100 "text-align: right; }\n"
102 <<
"<title>sdsl memory usage visualization</title>\n"
103 <<
"<script src=\"http://d3js.org/d3.v3.js\"></script>\n"
105 <<
"<body marginwidth=\"0\" marginheight=\"0\">\n"
106 <<
"<button><a id=\"download\">Save as SVG</a></button>\n"
107 <<
"<div class=\"chart\"><div id=\"visualization\"></div></div><script>\n";
108 return jsonheader.str();
113 std::stringstream jsonbody;
114 jsonbody <<
"var events = " << jsonObject <<
";\n"
115 <<
"var w = window,d = document,e = d.documentElement,g = d.getElementsByTagName('body')[0],\n"
116 <<
" xw = w.innerWidth || e.clientWidth || g.clientWidth,\n"
117 <<
" yh = w.innerHeight || e.clientHeight || g.clientHeight;\n\n"
118 <<
"var margin = {top: 20,right: 80,bottom: 120,left: 120},\n"
119 <<
" width = xw - margin.left - margin.right,height = yh - margin.top - margin.bottom;\n"
120 <<
"var x = d3.scale.linear().range([0, width]);\n"
121 <<
"var y = d3.scale.linear().range([height, 0]);\n"
122 <<
"var xAxis = d3.svg.axis().scale(x).orient(\"bottom\");\n"
123 <<
"var yAxis = d3.svg.axis().scale(y).orient(\"left\").ticks(5);\n"
124 <<
"var color = d3.scale.category10();\n"
125 <<
"var x_max = d3.max(events, function (d) { return d3.max(d.usage, function (u) { return u[0] / "
127 <<
"var y_max = d3.max(events, function (d) { return d3.max(d.usage, function (u) { return 1.1 * u[1] / "
128 "(1024 * 1024);})})\n"
129 <<
"var peak = d3.max(events, function (d) { return d3.max(d.usage, function (u) { return u[1]; })})\n"
130 <<
"var data = []\nevents.forEach(function (d) { data = data.concat(d.usage); });\n"
131 <<
"var peakelem = data.filter(function (a) { return a[1] == peak; });\n"
132 <<
"var peakelem = peakelem.splice(0,1);\n"
133 <<
"x.domain([0, x_max]);\n y.domain([0, y_max]);\n"
134 <<
"var svg = d3.select(\"#visualization\").append(\"svg\")\n"
135 <<
" .attr(\"width\", width + margin.left + margin.right)\n"
136 <<
" .attr(\"height\", height + margin.top + margin.bottom)\n"
137 <<
" .attr(\"xmlns\", \"http://www.w3.org/2000/svg\")\n"
138 <<
" .append(\"g\").attr(\"transform\",\"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n"
139 <<
" svg.append(\"g\").attr(\"class\", \"xaxis\").attr(\"transform\", \"translate(0,\" + height + "
141 <<
" .call(xAxis).append(\"text\").attr(\"text-anchor\", \"end\")\n"
142 <<
" .attr(\"shape-rendering\", \"crispEdges\").attr(\"x\", width / 2 + 50).attr(\"y\", "
143 "70).attr(\"shape-rendering\", \"crispEdges\")\n"
144 <<
" .attr(\"font-family\", \"sans-serif\").attr(\"font-size\", \"20px\").text(\"Time (seconds)\");\n\n"
145 <<
"svg.append(\"g\").attr(\"class\", \"yaxis\").call(yAxis).append(\"text\").attr(\"transform\", "
146 "\"rotate(-90)\").attr(\"x\", -height / 2 + 50)\n"
147 <<
" .attr(\"y\", -80).attr(\"shape-rendering\", \"crispEdges\").attr(\"font-family\", "
148 "\"sans-serif\").attr(\"font-size\", \"20px\").style(\"text-anchor\", \"end\")\n"
149 <<
" .text(\"Memory Usage (MiB)\");\n\n"
150 <<
"svg.selectAll(\".tick text\").style(\"font-size\", \"20px\");\n"
151 <<
"svg.selectAll(\".xaxis .tick text\").attr(\"dy\", 23);\nsvg.selectAll(\".yaxis .tick "
152 "text\").attr(\"dx\", -10);\n"
153 <<
"svg.selectAll(\"line\").attr(\"fill\", \"none\").attr(\"stroke\", "
154 "\"black\")\nsvg.selectAll(\"path\").attr(\"fill\", \"none\").attr(\"stroke\", \"black\")\n\n"
155 <<
"svg.selectAll(\"line.horizontalGrid\").data(y.ticks(5)).enter().append(\"line\")\n"
156 <<
" .attr({\"class\": \"horizontalGrid\",\"x1\": 0,\"x2\": width,\"y1\": function (d) { return y(d);},\n"
157 <<
" \"y2\": function (d) { return y(d); }, \"fill\": \"none\", \"shape-rendering\": \"crispEdges\",\n"
158 <<
" \"stroke\": \"lightgrey\",\"stroke-dasharray\": \"10,10\",\"stroke-width\": \"1.5px\"});\n\n"
159 <<
"var area = d3.svg.area().x(function (d) { return x(d[0] / 1000);}).y0(height).y1(function (d) { "
160 "return y(d[1] / (1024 * 1024))});\n\n"
161 <<
"var ev = svg.selectAll(\".event\").data(events).enter().append(\"svg:path\").attr(\"class\", "
163 <<
" .attr(\"fill\", function (d) { return d3.rgb(color(d.name)); })\n"
164 <<
" .attr(\"d\", function (d) { return area(d.usage) })\n"
165 <<
" .style(\"stroke\", function (d) { return d3.rgb(color(d.name)).darker(2);}).style(\"stroke-width\", "
167 <<
"svg.selectAll(\".dot\").data(peakelem).enter().append(\"circle\").attr(\"r\", 3).attr(\"fill\", "
169 <<
" .attr(\"cx\", function (d) {return x(d[0] / 1000)})\n"
170 <<
" .attr(\"cy\", function (d) {return y(d[1] / (1024 * 1024))})\n"
171 <<
" .attr(\"fill\", \"red\").attr(\"stroke-width\", 2).attr(\"stroke\", \"#cc0000\")\n\n"
172 <<
"svg.selectAll(\".dot\").data(peakelem).enter().append(\"svg:text\")\n"
173 <<
" .attr(\"x\", function (d) {return x(d[0] / 1000)}).attr(\"y\", function (d) {return y(d[1] / (1024 "
174 "* 1024) * 1.025)})\n"
175 <<
" .text(function (d) {return \"Peak Usage: \" + Math.round(d[1] / (1024 * 1024)) + \" MB\"})\n"
176 <<
" .attr(\"font-size\", 12).attr(\"fill\", \"red\");\n\n"
177 <<
"svg.selectAll(\".dot\").data(peakelem).enter().append(\"circle\")\n"
178 <<
" .attr(\"r\", 5).attr(\"fill\", \"red\")\n"
179 <<
" .attr(\"cx\", function (d) {return x(d[0] / 1000)})\n"
180 <<
" .attr(\"cy\", function (d) {return y(d[1] / (1024 * 1024))})\n"
181 <<
" .attr(\"fill\", \"none\").attr(\"stroke-width\", 2).attr(\"stroke\", "
182 "\"#cc0000\").each(pulsepeak());\n\n"
183 <<
"function pulsepeak() { return function (d, i, j) {\n"
184 <<
" d3.select(this).attr(\"r\", 5).style(\"stroke-opacity\", 1.0).transition()\n"
185 <<
" .ease(\"linear\").duration(1000).attr(\"r\", 10).style(\"stroke-opacity\", 0.0).each(\"end\", "
186 "pulsepeak());};}\n\n"
187 <<
"var vertical = d3.select(\".chart\").append(\"div\").attr(\"class\", \"remove\")\n"
188 <<
" .style(\"position\", \"absolute\").style(\"z-index\", \"19\").style(\"width\", \"1px\")\n"
189 <<
" .style(\"height\", height - margin).style(\"top\", \"30px\").style(\"bottom\", \"50px\")\n"
190 <<
" .style(\"left\", \"0px\").style(\"opacity\", \"0.4\").style(\"background\", \"black\");\n\n"
191 <<
"var tooltip = d3.select(\".chart\").append(\"div\").attr(\"class\", \"remove\")\n"
192 <<
" .style(\"position\", \"absolute\").style(\"z-index\", \"20\").style(\"visibility\", "
193 "\"hidden\").style(\"top\", \"10px\");\n\n"
194 <<
"var circle = svg.append(\"circle\").attr(\"cx\", 100).attr(\"cy\", 350).attr(\"r\", 3).attr(\"fill\", "
195 "\"black\").style(\"opacity\", \"0\")\n\n"
196 <<
"d3.select(\"svg\").on(\"mousemove\", function () {\n"
197 <<
" mousex = d3.mouse(this);\n"
198 <<
" if (mousex[0] < margin.left + 3 || mousex[0] >= xw - margin.right) {\n"
199 <<
" vertical.style(\"opacity\", \"0\"); tooltip.style(\"opacity\", \"0\"); circle.style(\"opacity\", "
202 <<
" var xvalue = x.invert(mousex[0] - margin.left); var pos = findPosition(xvalue)\n"
203 <<
" vertical.style(\"opacity\", \"0.4\"); tooltip.style(\"opacity\", \"1\"); "
204 "circle.style(\"opacity\", \"1\")\n"
205 <<
" circle.attr(\"cx\", pos.x).attr(\"cy\", pos.y); vertical.style(\"left\", mousex[0] + "
206 "\"px\");tooltip.style(\"left\", mousex[0] + 15 + \"px\")\n"
207 <<
" tooltip.html(\"<p>\" + xvalue.toFixed(2) + \" Seconds <br>\" + Math.round(pos.mem) + \" MiB <br> "
209 <<
" \"<br> Phase Time: \" + pos.ptime + \" Seconds </p>\").style(\"visibility\", \"visible\");\n"
211 <<
".on(\"mouseover\", function () {\n"
212 <<
" mousex = d3.mouse(this);\n if (mousex[0] < margin.left + 3 || mousex[0] > xw - margin.right) {\n"
213 <<
" vertical.style(\"opacity\", \"0\")\n } else {\n vertical.style(\"opacity\", "
214 "\"0.4\");vertical.style(\"left\", mousex[0] + 7 + \"px\")\n}})\n"
215 <<
"d3.select(\"#download\").on(\"click\", function () {\n"
216 <<
"d3.select(this).attr(\"href\", 'data:application/octet-stream;base64,' + "
217 "btoa(d3.select(\"#visualization\").html())).attr(\"download\", \"viz.svg\")})\n\n"
219 "findPosition(e){correctArea=d3.selectAll(\".area\").filter(function(t){if(t.usage[0][0]<=e*1e3&&t."
220 "usage[t.usage.length-1][0]>=e*1e3){return true}"
221 <<
"return false});if(correctArea.empty()){return 0}var t=new "
222 "Array;correctArea[0].forEach(function(n){t.push(findYValueinArea(n,e))});"
223 <<
"max_elem=d3.max(t,function(e){return e.mem});var n=t.filter(function(e){return "
224 "e.mem==max_elem});return n[0]}"
225 <<
"function findYValueinArea(e,t){len=e.getTotalLength();var n=0;var r=len;for(var i=0;i<=len;i+=50){var "
226 "s=e.getPointAtLength(i);"
227 <<
"var o=x.invert(s.x);var u=y.invert(s.y);if(u>0&&o>t){n=Math.max(0,i-50);r=i;break}}var "
228 "a=e.getPointAtLength(0);"
229 <<
"var f=1;while(n<r){var "
231 "2;a=e.getPointAtLength(l);target_x=x.invert(a.x);if((l==n||l==r)&&Math.abs(target_x-t)>.01){break}if("
233 <<
"else if(target_x<t)n=l;else{break}if(f>50){break}f++}var c=new "
234 "function(){this.mem=y.invert(a.y);this.name=e.__data__.name;"
235 <<
"this.min=d3.min(e.__data__.usage,function(e){return "
236 "e[0]/1e3});this.max=d3.max(e.__data__.usage,function(e){return e[0]/1e3});"
237 <<
"this.ptime=Math.round(this.max-this.min);this.x=a.x;this.y=a.y};return c}\n</script></body></html>";
238 return jsonbody.str();
244 std::stringstream json_data;
265#define ALIGNMENT sizeof(uint64_t)
266#define ALIGNSPLIT(size) (((size)) & ~0x7)
267#define ALIGN(size) (((size) + (ALIGNMENT - 1)) & ~0x7)
268#define MM_BLOCK_OVERHEAD (sizeof(size_t) + sizeof(size_t))
269#define MIN_BLOCKSIZE (ALIGN(sizeof(mm_block_t) + sizeof(mm_block_foot_t)))
270#define UNMASK_SIZE(size) ((size) & ~1)
271#define ISFREE(size) ((size)&1)
272#define SETFREE(size) ((size) | 1)
273#define SPLIT_THRESHOLD (MIN_BLOCKSIZE)
285 if (cur_bptr == first)
296 if ((uint8_t *)((uint8_t *)cur_bptr +
UNMASK_SIZE(cur_bptr->
size)) >= top)
312 return ((ptr->
size) & 1ULL);
350 return (
void *)((uint8_t *)ptr +
sizeof(
size_t));
377 uint8_t * m_base =
nullptr;
379 uint8_t * m_top =
nullptr;
380 size_t m_total_size = 0;
381 std::multimap<size_t, mm_block_t *> m_free_large;
384 inline void block_print(
int id,
mm_block_t * bptr)
387 "%d addr=%p size=%lu (%lu) free=%d\n",
396 inline uint64_t extract_number(std::string & line)
399 for (
size_t i = line.size() - 1; i + 1 >= 1; i--)
401 if (isdigit(line[i]))
403 num_str.insert(num_str.begin(), line[i]);
407 if (num_str.size() > 0)
413 return std::strtoull(num_str.c_str(),
nullptr, 10);
416 inline uint64_t extract_multiplier(std::string & line)
419 if (line[line.size() - 2] ==
'k' || line[line.size() - 2] ==
'K')
423 if (line[line.size() - 2] ==
'm' || line[line.size() - 2] ==
'M')
427 if (line[line.size() - 2] ==
'g' || line[line.size() - 2] ==
'G')
429 num = 1024 * 1024 * 1024;
434 size_t determine_available_hugepage_memory()
437 size_t page_size_in_bytes = 0;
438 size_t num_free_pages = 0;
439 const std::string meminfo_file =
"/proc/meminfo";
440 const std::string ps_str =
"Hugepagesize:";
441 const std::string pf_str =
"HugePages_Free:";
442 std::ifstream mifs(meminfo_file);
447 while (std::getline(mifs, line))
449 auto ps = std::mismatch(ps_str.begin(), ps_str.end(), line.begin());
450 if (ps.first == ps_str.end())
452 page_size_in_bytes = extract_number(line) * extract_multiplier(line);
454 auto pf = std::mismatch(pf_str.begin(), pf_str.end(), line.begin());
455 if (pf.first == pf_str.end())
457 num_free_pages = extract_number(line);
464 throw std::system_error(ENOMEM,
465 std::system_category(),
466 "hugepage_allocator could not automatically determine available hugepages");
479 remove_from_free_set(next);
488 remove_from_free_set(prev);
495 insert_into_free_set(newblock);
516 coalesce_block(newblock);
520 uint8_t * hsbrk(
size_t size)
522 ptrdiff_t left = (ptrdiff_t)m_total_size - (m_top - m_base);
523 if (left < (ptrdiff_t)
size)
525 throw std::system_error(ENOMEM,
526 std::system_category(),
527 "hugepage_allocator: not enough hugepage memory available");
529 uint8_t * new_mem = m_top;
548 auto eq_range = m_free_large.equal_range(block->
size);
550 auto itr = eq_range.first;
551 auto last = eq_range.second;
552 auto found = m_free_large.end();
555 if (itr->second == block)
561 if (found == m_free_large.end())
565 m_free_large.erase(found);
572 m_free_large.insert({block->
size, block});
581 if (free_block != m_free_large.end())
583 bptr = free_block->second;
584 m_free_large.erase(free_block);
611 block_print(
id, bptr);
628 mmap(
nullptr, m_total_size, (PROT_READ | PROT_WRITE), (MAP_HUGETLB | MAP_ANONYMOUS | MAP_PRIVATE), 0, 0);
629 if (m_base == MAP_FAILED)
631 throw std::system_error(ENOMEM, std::system_category(),
"hugepage_allocator could not allocate hugepages");
640 throw std::system_error(ENOMEM,
641 std::system_category(),
642 "hugepage_allocator: MAP_HUGETLB / hugepage support not available");
660 bool need_malloc = 0;
663 if (
size == blockdatasize)
668 if (
size < blockdatasize)
673 split_block(bptr,
size);
686 size_t needed =
ALIGN(
size - blockdatasize);
702 remove_from_free_set(next);
721 remove_from_free_set(prev);
726 ptr = memmove(
block_data(prev), ptr, blockdatasize);
746 memcpy(newptr, ptr,
size);
779 remove_from_free_set(bptr);
804 coalesce_block(bptr);
816 if (ptr >= m_base && ptr < m_top)
833 bool hugepages =
false;
846 auto & m = the_manager();
857 auto & m = the_manager();
869 auto & m = the_manager();
875 return (uint64_t *)realloc(ptr,
size);
882 auto & m = the_manager();
886 throw std::runtime_error(std::string(
"hugepages not supported on Windows"));
891 template <
class t_vec>
892 static void resize(t_vec & v,
const typename t_vec::size_type capacity)
894 uint64_t old_capacity_in_bytes = ((v.m_capacity + 63) >> 6) << 3;
895 uint64_t new_capacity_in_bytes = ((capacity + 63) >> 6) << 3;
896 bool do_realloc = old_capacity_in_bytes != new_capacity_in_bytes;
897 v.m_capacity = ((capacity + 63) >> 6) << 6;
899 if (do_realloc || v.m_data ==
nullptr)
905 size_t allocated_bytes = (size_t)(((v.m_capacity + 64) >> 6) << 3);
907 if (allocated_bytes != 0 && v.m_data ==
nullptr)
909 throw std::bad_alloc();
919 template <
class t_vec>
942 if (!(mode & std::ios_base::out))
943 _sopen_s(&fd, filename.c_str(), _O_BINARY | _O_RDONLY, _SH_DENYNO, _S_IREAD);
945 _sopen_s(&fd, filename.c_str(), _O_BINARY | _O_RDWR, _SH_DENYNO, _S_IREAD | _S_IWRITE);
948 if (!(mode & std::ios_base::out))
949 return open(filename.c_str(), O_RDONLY);
951 return open(filename.c_str(), O_RDWR);
956 static void *
mmap_file(
int fd, uint64_t file_size, std::ios_base::openmode mode)
960 std::cout <<
"file_size=0" << std::endl;
968 return file_content.data();
972 HANDLE fh = (HANDLE)_get_osfhandle(fd);
973 if (fh == INVALID_HANDLE_VALUE)
978 if (!(mode & std::ios_base::out))
980 fm = CreateFileMapping(fh, NULL, PAGE_READONLY, 0, 0, NULL);
983 fm = CreateFileMapping(fh, NULL, PAGE_READWRITE, 0, 0, NULL);
988 void * map =
nullptr;
989 if (!(mode & std::ios_base::out))
991 map = MapViewOfFile(fm, FILE_MAP_READ, 0, 0, file_size);
994 map = MapViewOfFile(fm, FILE_MAP_WRITE | FILE_MAP_READ, 0, 0, file_size);
1002 void * map =
nullptr;
1003 if (!(mode & std::ios_base::out))
1004 map = mmap(NULL, file_size, PROT_READ, MAP_SHARED, fd, 0);
1006 map = mmap(NULL, file_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
1007 if (map == MAP_FAILED)
1016 if (addr ==
nullptr)
1026 if (UnmapViewOfFile(addr))
1030 return munmap(addr,
size);
1056 auto ret = _chsize_s(fd, new_size);
1061 return ftruncate(fd, new_size);
1070#undef MM_BLOCK_OVERHEAD
1075#undef SPLIT_THRESHOLD
void init(SDSL_UNUSED size_t size_in_bytes=0)
void * mm_realloc(void *ptr, size_t size)
void * mm_alloc(size_t size_in_bytes)
static hugepage_allocator & the_allocator()
bool in_address_space(void *ptr)
static uint64_t * alloc_mem(size_t size_in_bytes)
static uint64_t * realloc_mem(uint64_t *ptr, size_t size)
static void * mmap_file(int fd, uint64_t file_size, std::ios_base::openmode mode)
static int close_file_for_mmap(int fd)
static void use_hugepages(size_t bytes=0)
static void free_mem(uint64_t *ptr)
static int mem_unmap(int fd, void *addr, const uint64_t size)
static int open_file_for_mmap(std::string &filename, std::ios_base::openmode mode)
static void resize(t_vec &v, const typename t_vec::size_type capacity)
static int truncate_file_mmap(int fd, const uint64_t new_size)
static void clear(t_vec &v)
static void record(int64_t delta)
#define MM_BLOCK_OVERHEAD
#define UNMASK_SIZE(size)
memory_tracking.hpp contains two function for allocating and deallocating memory
size_t file_size(std::string const &name)
Get the file size.
content_type & content(std::string const &name)
Get the content.
int close(int const fd)
Get fd for file.
int truncate(int const fd, size_t new_size)
Get the content with fd.
int open(std::string const &name)
Get fd for file.
Namespace for the succinct data structure library.
size_t block_size(void *ptr)
mm_block_t * block_prev(mm_block_t *cur_bptr, mm_block_t *first)
std::string create_mem_html_header()
void block_markused(mm_block_t *ptr)
void * block_data(mm_block_t *ptr)
mm_block_t * block_next(mm_block_t *cur_bptr, uint8_t *top)
void block_markfree(mm_block_t *ptr)
bool block_prevfree(mm_block_t *ptr, mm_block_t *begin)
void write_mem_log< HTML_FORMAT >(std::ostream &out, tracker_storage const &m)
bool block_nextfree(mm_block_t *ptr, uint8_t *top)
struct sdsl::mm_block mm_block_t
void foot_update(mm_block_t *ptr, size_t size)
std::string create_mem_js_body(std::string const &jsonObject)
T::size_type size_in_bytes(T const &t)
Get the size of a data structure in bytes.
struct sdsl::bfoot mm_block_foot_t
size_t block_getdatasize(mm_block_t *ptr)
void block_update(mm_block_t *ptr, size_t size)
bool is_ram_file(std::string const &file)
Determines if the given file is a RAM-file.
int_vector ::size_type size(range_type const &r)
Size of a range.
void output_event_json(std::ostream &out, mm_event const &ev, tracker_storage const &m)
bool block_isfree(mm_block_t *ptr)
void write_mem_log< JSON_FORMAT >(std::ostream &out, tracker_storage const &m)
mm_block_t * block_cur(void *ptr)
std::vector< mm_alloc > allocations
std::vector< mm_event > completed_events
timer::time_point start_log