Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 27 May 2004 14:20:40 -0400
From:      Charles Swiger <cswiger@mac.com>
To:        Michael Sig Birkmose <michael@gisp.dk>
Cc:        freebsd-questions@freebsd.org
Subject:   Re: Measuring the stack usage of a program
Message-ID:  <8EF1411C-B00A-11D8-AA39-003065ABFD92@mac.com>
In-Reply-To: <20040527010804.M72742@server.gisp.dk>
References:  <20040527010804.M72742@server.gisp.dk>

next in thread | previous in thread | raw e-mail | index | archive | help
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



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?8EF1411C-B00A-11D8-AA39-003065ABFD92>