如何测量Rust中的函数堆栈使用情况?

时间:2016-08-13 05:27:02

标签: rust stack-memory

有没有办法可以衡量一个函数使用多少堆栈内存?

这个问题不是特定于递归函数;但我有兴趣知道递归函数会占用多少堆栈内存。

我有兴趣优化堆栈内存使用的功能;然而,在不知道编译器已经进行了哪些优化的情况下,如果这是在做出真正的改进,那只是猜测。

要明确的是,是关于如何优化以更好地使用堆栈的问题。

那么是否有一些可靠的方法可以找出函数在Rust中使用多少堆栈内存?

请注意,其他编译器支持此功能,GCC例如-fstack-usage

1 个答案:

答案 0 :(得分:2)

作为最后的手段,您可以观察堆栈指针(使用内联汇编)并从中推断出结果。这种方法绝对不是你在生产中使用的东西......但它有效。

#![feature(asm)]

use std::cell::Cell;
use std::cmp;
use std::usize;

// This global variable tracks the highest point of the stack
thread_local!(static STACK_END: Cell<usize> = Cell::new(usize::MAX));

macro_rules! stack_ptr {
    () => ({
        // Grab a copy of the stack pointer
        let x: usize;
        unsafe {
            asm!("mov %rsp, $0" : "=r"(x) ::: "volatile");
        }
        x
    })
}

/// Saves the current position of the stack. Any function
/// being profiled must call this macro.
macro_rules! tick {
    () => ({
        // Save the current stack pointer in STACK_END
        let stack_end = stack_ptr!();
        STACK_END.with(|c| {
            // Since the stack grows down, the "tallest"
            // stack must have the least pointer value
            let best = cmp::min(c.get(), stack_end);
            c.set(best);
        });
    })
}

/// Runs the given callback, and returns its maximum stack usage
/// as reported by the `tick!()` macro.
fn measure<T, F: FnOnce() -> T>(callback: F) -> (T, usize) {
    STACK_END.with(|c| c.set(usize::MAX));
    let stack_start = stack_ptr!();
    let r = callback();
    let stack_end = STACK_END.with(|c| c.get());
    if stack_start < stack_end {
        panic!("tick!() was never called");
    }
    (r, stack_start - stack_end)
}

/// Example recursive function
fn fibonacci(n: i64) -> i64 {
    tick!();
    match n {
        0 => 0,
        1 => 1,
        _ => fibonacci(n-1) + fibonacci(n-2)
    }
}

fn main() {
    // Stack usage should grow linearly with `i`
    for i in 0 .. 10 {
        let (result, stack) = measure(|| fibonacci(i));
        println!("fibonacci({}) = {}: used {} bytes of stack", i, result, stack);
    }
}