Let us consider the following factorial example :
#include <iostream.h>
int factorial(int);
void main(void) {
int number;
cout << "Please enter a positive integer: ";
cin >> number;
if (number < 0)
cout << "That is not a positive integer.\n";
else
cout << number << " factorial is: " << factorial(number) << endl;
}
int factorial(int number) {
int temp;
if(number <= 1) return 1;
temp = number * factorial(number - 1);
return temp;
}
How can I compute the memory used the function factorial() ? To be more precise I want to know how much memory the function uses ?
EDIT:
This is just a sample program and the program I’m working on is lot different and has many functions and I actually want to calculate the memory usage of every functions.
For my second answer (prompted by the comments to my first answer), you could use a function that computes how much of the stack has been touched. Here’s one that hopefully doesn’t make too many assumptions about the nature of the stack on a given architecture. It assumes a descending stack, which is a fairly safe bet for most people:
You call it once before the function you want to test, and once after. The second call will return how many bytes of the stack have been touched (minus some constant value that you’ll have to determine experimentally). You have to make sure that only the code you are testing runs between the two calls to
depth():You also have to watch out for edge cases. For instance, if
numberis 0 or 1, the depth test fails for reasons I haven’t figured out yet. And goodness knows what will happen if the compiler starts reusing stack slots. In a nutshell: caveat emptor.Notes:
srand()/rand()or their thread-safe counterparts will probably work fine, but I wanted to avoid calling any function other thanalloca().unsigned long r = (unsigned long)&r;avoids the constant seed for slightly more randomness, and it works since if the two calls todepth()are made at different stack depths, this technique will fail anyway. I just don’t know how safe the seeds thus generated will be.