简体   繁体   中英

How to track a recursive function's call stack usage

I am teaching a class to intro C++ students and I want to design a lab that shows how recursive functions differ from iteration. My idea was to track the memory/call stack usage for both and display the difference. I was almost positive that I had done something similar when I did my degree, but can't remember. My experience doesn't lie in C/C++ so any guidance would be appreciated.

Update 1:

I believe I may have miss represented my task. I had hoped to find a way to show how recursion increases the overhead/stack compared to iteration. I followed some suggested links and came up with the following script.

loops=100
counter=0
total1=0
echo "Iteration"
while [ $counter -lt $loops ]; do
    "$1" & # Run the given command line in the background.
    pid=$! peak1=0
    echo -e "$counter.\c"
    while true; do
    #sleep 0.1
        sample="$(pmap $pid | tail -n1 | sed 's/[^0-9]*//g' 2> /dev/null)" || break

        if [ -z "$sample" ]; then
            break
        fi
        let peak1='sample > peak1 ? sample : peak1'
    done
#    echo "Peak: $peak1" 1>&2
    total1=$(expr $total1 + $peak1)
    counter=$[$counter+1]
done

The program implements a binary search with either iteration or recursion. The idea is to get the average memory use and compare it to the Recursion version of the same program. This does not work as the iteration version often has a larger memory average than the recursion, which doesn't show to my students that recursion has drawbacks. Therefore I am pretty sure I am doing something incorrect.

Is pmap not going to provide me with what I want?

Something like this I think

void recursive(int* ptop) {
  int dummy = 0; 
  printf("stack size %d\n",&dummy - ptop);
  recursive(ptop);
}

void start() {
  int dummy = 0;      
  recursive(&dummy);
}

until it will crash.

在了解它们的任何平台上(Linux), backtrace(3)甚至更好的backtrace_symbols(3)及其同伴都应该有很大的帮助。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM