|
| 1 | + |
| 2 | + |
| 3 | +#include "mem_usage.hpp" |
| 4 | + |
| 5 | +namespace intel_npu { |
| 6 | + |
| 7 | +#if defined _WIN32 |
| 8 | + |
| 9 | +#include <windows.h> |
| 10 | +#include <psapi.h> |
| 11 | + |
| 12 | +int64_t get_peak_memory_usage() { |
| 13 | + PROCESS_MEMORY_COUNTERS mem_counters; |
| 14 | + if (!GetProcessMemoryInfo(GetCurrentProcess(), &mem_counters, sizeof(mem_counters))) { |
| 15 | + throw std::runtime_error("Can't get system memory values"); |
| 16 | + } |
| 17 | + |
| 18 | + // Linux tracks memory usage in pages and then converts them to kB. |
| 19 | + // Thus, there is always some room for inaccuracy as pages are not guaranteed to be fully used. |
| 20 | + // In Windows, the situation is different: the system returns the memory usage in bytes, not in pages. |
| 21 | + // To align the output between the two operating systems as closely as possible, we have two options: |
| 22 | + // 1. Use rounding to the nearest integer. |
| 23 | + // 2. Try to estimate the number of pages used in Windows. However, |
| 24 | + // this approach is likely to be inaccurate as well, so option 1 was chosen. |
| 25 | + static constexpr double bytes_in_kilobyte = 1024.0; |
| 26 | + |
| 27 | + // please note then we calculate difference |
| 28 | + // to get peak memory increment value, so we return int64, not size_t |
| 29 | + return static_cast<int64_t>(std::round(mem_counters.PeakWorkingSetSize / bytes_in_kilobyte)); |
| 30 | +} |
| 31 | + |
| 32 | +#else |
| 33 | + |
| 34 | +#include <fstream> |
| 35 | +#include <regex> |
| 36 | +#include <sstream> |
| 37 | + |
| 38 | +int64_t get_peak_memory_usage() { |
| 39 | + size_t peak_mem_usage_kB = 0; |
| 40 | + |
| 41 | + std::ifstream status_file("/proc/self/status"); |
| 42 | + std::string line; |
| 43 | + std::regex vm_peak_regex("VmPeak:"); |
| 44 | + std::smatch vm_match; |
| 45 | + bool mem_values_found = false; |
| 46 | + while (std::getline(status_file, line)) { |
| 47 | + if (std::regex_search(line, vm_match, vm_peak_regex)) { |
| 48 | + std::istringstream iss(vm_match.suffix()); |
| 49 | + iss >> peak_mem_usage_kB; |
| 50 | + mem_values_found = true; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + if (!mem_values_found) { |
| 55 | + throw std::runtime_error("Can't get system memory values"); |
| 56 | + } |
| 57 | + |
| 58 | + // please note then we calculate difference |
| 59 | + // to get peak memory increment value, so we return int64, not size_t |
| 60 | + return static_cast<int64_t>(peak_mem_usage_kB); |
| 61 | +} |
| 62 | + |
| 63 | +#endif |
| 64 | +} |
0 commit comments