0

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?

Community
  • 1
  • 1
Eric Ianni
  • 75
  • 1
  • 7
  • Use [gdb](https://www.gnu.org/software/gdb/)'s [`backtrace`](https://sourceware.org/gdb/onlinedocs/gdb/Backtrace.html)? – Anmol Singh Jaggi Mar 05 '16 at 02:09
  • Short version ps or `sysinfo.h`. Check http://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process and http://stackoverflow.com/questions/131303/how-to-measure-actual-memory-usage-of-an-application-or-process. – knightrider Mar 05 '16 at 02:14

2 Answers2

3

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.

c-smile
  • 26,734
  • 7
  • 59
  • 86
0

On any platform that knows them (Linux), backtrace(3), or even better backtrace_symbols(3) and their companions should be of great help.

tofro
  • 5,640
  • 14
  • 31