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

8
有没有办法测量一个函数使用了多少堆栈内存?
这个问题不仅仅适用于递归函数;然而我很想知道一个被递归调用的函数需要多少堆栈内存。
我想要优化函数的堆栈内存使用;但是,如果不知道编译器已经做了哪些优化,那么这只是瞎猜是否会有真正的改进。
明确一点,这不是关于如何优化更好地使用堆栈的问题。
那么在Rust中有没有一种可靠的方法来查找一个函数使用了多少堆栈内存?
请注意,其他编译器支持此功能,例如GCC提供了“-fstack-usage”选项。

2个回答

4
作为最后的手段,您可以观察堆栈指针(使用内联汇编),并从中推断出结果。这种方法绝对不是您在生产中使用的...但它可以工作。
#![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);
    }
}

1
截至今日,有一些实验性工具可用于估算堆栈使用情况:https://crates.io/crates/cargo-call-stack。它使用实验性的-Z emit-stack-sizes来获取每个函数的堆栈,然后设法提取调用图,并从中生成最坏情况的估计。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接