Measuring the stack usage of a program
Charles Swiger
cswiger at mac.com
Sat May 29 23:57:14 PDT 2004
On May 26, 2004, at 7:09 PM, Michael Sig Birkmose wrote:
> Does anyone know, if it is possible to meassure the maximum stack
> usage of
> a C program throughout it's entire execution?
Sure. See "man getrusage", specificly:
long ru_isrss; /* integral unshared stack size */
...which tends to give you the maximum usage on most systems (because
they don't shrink the stack if it becomes smaller). You can also
compare the addresses of automatic variables within the code of the
program itself to see how the stack grows:
/* Test program to measure stack usage... */
void *
test_function(int count)
{
int foo = 1;
#if 0 /* make the local frame much bigger */
char buf[1000];
sprintf(buf, "%d\n", count);
#endif
if (count > 0) {
return test_function(count - 1);
} else
return &foo;
}
int
main(int argc, char *argv[])
{
int depth = 100;
unsigned long delta;
if (argc > 1) depth = atoi(argv[1]);
delta = (unsigned long)&depth - (unsigned long)test_function(depth);
printf("\nchange in stack size: %lu bytes.\n", delta);
return 0;
}
[ Yeah, yeah, I should use ptrdiff_t, but you get the idea... ]
--
-Chuck
More information about the freebsd-questions
mailing list