@@ -203,24 +203,60 @@ void StackSampler::set_mask(bool mask)
203203 get ().discard = mask;
204204}
205205
206- std::string HeapDiag::to_string ()
207- {
208- static intptr_t last = 0 ;
206+
207+ inline std::string to_human_size (std::uint64_t bytes) {
208+ constexpr std::string_view size_suffixes[] = {
209+ " B" , " KiB" , " MiB" , " GiB" , " TiB" , " PiB"
210+ };
211+ double value = static_cast <double >(bytes);
212+ std::size_t exponent = 0 ;
213+
214+ while (value >= 1024.0 && exponent + 1 < std::size (size_suffixes)) {
215+ value /= 1024.0 ;
216+ exponent++;
217+ }
218+
219+ if (exponent == 0 )
220+ return std::format (" {} {}" , static_cast <std::uint64_t >(value), size_suffixes[exponent]);
221+ else
222+ return std::format (" {:.2f} {}" , value, size_suffixes[exponent]);
223+ }
224+
225+ inline std::string with_thousands_sep (uint64_t value, char sep = ' _' , char every = 3 ) {
226+ std::string s = std::to_string (value);
227+ for (int i = s.size () - every; i > 0 ; i -= every)
228+ s.insert (i, 1 , sep);
229+ return s;
230+ }
231+
232+ std::string HeapDiag::to_string () {
233+ // TODO: check if heap should be 64 bit instead
234+ static intptr_t last_size = 0 ;
235+
209236 // show information on heap status, to discover leaks etc.
210- auto heap_begin = kernel::heap_begin ();
211- auto heap_end = kernel::heap_end ();
212- auto heap_usage = kernel::heap_usage ();
213- intptr_t heap_size = heap_end - heap_begin;
214- last = heap_size - last;
215-
216- char buffer[256 ];
217- int len = snprintf (buffer, sizeof (buffer),
218- " Heap begin %#lx size %lu Kb\n "
219- " Heap end %#lx diff %lu (%ld Kb)\n "
220- " Heap usage %lu kB\n " ,
221- heap_begin, heap_size / 1024 ,
222- heap_end, last, last / 1024 ,
223- heap_usage / 1024 );
224- last = (int32_t ) heap_size;
225- return std::string (buffer, len);
237+ const uintptr_t heap_begin = kernel::heap_begin ();
238+ const uintptr_t heap_end = kernel::heap_end ();
239+ const size_t heap_usage = kernel::heap_usage ();
240+
241+ const size_t heap_size = heap_end - heap_begin;
242+ const size_t heap_growth = heap_size - last_size;
243+
244+ auto buffer = std::format (
245+ " Logged last size {} ({} bytes)\n "
246+ " Reported heap begin {:#010x}\n " // 32-bit system = 8 hex chars ("0x" += 2)
247+ " Reported heap end {:#010x}\n "
248+ " (end-begin) usage {} ({} bytes)\n "
249+ " Reported usage {} ({} bytes)\n "
250+ " Δ(end-begin) {} ({} bytes)\n "
251+ ,
252+ to_human_size (last_size), with_thousands_sep (last_size),
253+ heap_begin,
254+ heap_end,
255+ to_human_size (heap_size), with_thousands_sep (heap_size),
256+ to_human_size (heap_usage), with_thousands_sep (heap_usage),
257+ to_human_size (heap_growth), with_thousands_sep (heap_growth)
258+ );
259+
260+ last_size = (int32_t ) heap_size;
261+ return buffer;
226262}
0 commit comments