Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
logstr.cpp
Go to the documentation of this file.
1// logstr()
2// --------------------
3// Logs a message to stderr and appends the *peak* resident-set size (RSS)
4// of the current process in MiB.
5//
6// Windows note: link with Psapi.lib
7
8#include <cstddef>
9#include <iomanip>
10#include <iostream>
11
12#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__)
13#include <sys/resource.h>
14#elif defined(_WIN32)
15#define NOMINMAX
16#define PSAPI_VERSION 1
17#include <psapi.h>
18#include <windows.h>
19#endif
20
21namespace {
22//---------------------------------------------------------------------
23// peak_rss_bytes()
24//---------------------------------------------------------------------
25// Returns the *peak* RSS in **bytes** for the current process,
26// or 0 on failure / unsupported platform.
27//---------------------------------------------------------------------
28std::size_t peak_rss_bytes()
29{
30#if defined(_WIN32)
31 PROCESS_MEMORY_COUNTERS pmc{};
32 if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)))
33 return static_cast<std::size_t>(pmc.PeakWorkingSetSize);
34
35#elif defined(__APPLE__) || defined(__FreeBSD__)
36 struct rusage usage{};
37 if (getrusage(RUSAGE_SELF, &usage) == 0)
38 // ru_maxrss is already bytes on macOS / BSD
39 return static_cast<std::size_t>(usage.ru_maxrss);
40
41#elif defined(__linux__)
42 struct rusage usage{};
43 if (getrusage(RUSAGE_SELF, &usage) == 0)
44 // ru_maxrss is kilobytes on Linux → convert to bytes
45 return static_cast<std::size_t>(usage.ru_maxrss) * 1024ULL;
46#endif
47
48 return 0; // fallback on error / unknown OS
49}
50
51} // namespace
52
53//---------------------------------------------------------------------
54// C-linkage wrapper: log_with_mem_usage()
55//---------------------------------------------------------------------
56// Prints "<msg> (mem: <value> MiB)" with two-digit precision.
57//
58// • Safe to call from C, C++, or dlopen’d plugins.
59// • Thread-safe w.r.t. internal state; output lines may still
60// interleave if multiple threads call concurrently (as with any
61// stderr logging).
62//---------------------------------------------------------------------
63extern "C" void logstr(char const* msg)
64{
65 const std::size_t bytes = peak_rss_bytes();
66 std::cerr << msg;
67
68 if (bytes != 0) {
69 const double mib = static_cast<double>(bytes) / (1024.0 * 1024.0);
70 std::cerr << " (mem: " << std::fixed << std::setprecision(2) << mib << " MiB)";
71 } else {
72 std::cerr << " (mem: N/A)";
73 }
74 std::cerr << '\n';
75}
void logstr(char const *msg)
Definition logstr.cpp:63
constexpr decltype(auto) get(::tuplet::tuple< T... > &&t) noexcept
Definition tuple.hpp:13