9202: feat: Make `MemoryUsage` work on Windows r=jonas-schievink a=jonas-schievink

Unfortunately there is no convenient API for heap statistics, so this instead uses the Commit Charge value, which is the amount of memory that needs to be allocated either in physical RAM or in the page file. This approximation seems to be good enough to find queries that waste a large amount of memory, but it should generally be expected to be off by several MB.

bors r+

Co-authored-by: Jonas Schievink <jonasschievink@gmail.com>
This commit is contained in:
bors[bot] 2021-06-10 12:09:54 +00:00 committed by GitHub
commit f4da4de7cd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 20 additions and 0 deletions

1
Cargo.lock generated
View File

@ -1170,6 +1170,7 @@ dependencies = [
"once_cell",
"perf-event",
"tikv-jemalloc-ctl",
"winapi",
]
[[package]]

View File

@ -20,6 +20,9 @@ jemalloc-ctl = { version = "0.4.1", package = "tikv-jemalloc-ctl", optional = tr
[target.'cfg(target_os = "linux")'.dependencies]
perf-event = "0.4"
[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3.8", features = ["psapi"] }
[features]
cpu_profiler = []
jemalloc = ["jemalloc-ctl"]

View File

@ -35,6 +35,22 @@ impl MemoryUsage {
// Note: This is incredibly slow.
let alloc = unsafe { libc::mallinfo() }.uordblks as isize;
MemoryUsage { allocated: Bytes(alloc) }
} else if #[cfg(windows)] {
// There doesn't seem to be an API for determining heap usage, so we try to
// approximate that by using the Commit Charge value.
use winapi::um::processthreadsapi::*;
use winapi::um::psapi::*;
use std::mem::{MaybeUninit, size_of};
let proc = unsafe { GetCurrentProcess() };
let mut mem_counters = MaybeUninit::uninit();
let cb = size_of::<PROCESS_MEMORY_COUNTERS>();
let ret = unsafe { GetProcessMemoryInfo(proc, mem_counters.as_mut_ptr(), cb as u32) };
assert!(ret != 0);
let usage = unsafe { mem_counters.assume_init().PagefileUsage };
MemoryUsage { allocated: Bytes(usage as isize) }
} else {
MemoryUsage { allocated: Bytes(0) }
}