accel/memory/
info.rs

1use crate::{contexted_call, device::*};
2use cuda::*;
3use std::sync::Arc;
4
5/// Total and Free memory size of the device (in bytes)
6#[derive(Debug, Clone, Copy, PartialEq)]
7struct MemoryInfo {
8    free: usize,
9    total: usize,
10}
11
12impl MemoryInfo {
13    fn get(ctx: Arc<Context>) -> Self {
14        let mut free = 0;
15        let mut total = 0;
16        unsafe {
17            contexted_call!(
18                &ctx,
19                cuMemGetInfo_v2,
20                &mut free as *mut usize,
21                &mut total as *mut usize
22            )
23        }
24        .expect("Cannot get memory info");
25        MemoryInfo { free, total }
26    }
27}
28
29/// Get total memory size in bytes of the current device
30///
31/// Panic
32/// ------
33/// - when given context is not current
34pub fn total_memory(ctx: Arc<Context>) -> usize {
35    MemoryInfo::get(ctx).total
36}
37
38/// Get free memory size in bytes of the current device
39///
40/// Panic
41/// ------
42/// - when given context is not current
43pub fn free_memory(ctx: Arc<Context>) -> usize {
44    MemoryInfo::get(ctx).free
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50    use crate::error::*;
51
52    #[test]
53    fn info() -> Result<()> {
54        let device = Device::nth(0)?;
55        let ctx = device.create_context();
56        let mem_info = MemoryInfo::get(ctx);
57        dbg!(&mem_info);
58        assert!(mem_info.free > 0);
59        assert!(mem_info.total > mem_info.free);
60        Ok(())
61    }
62}