Measuring stack usage for Linux multi-threaded app

北城余情 提交于 2019-12-01 19:43:17

I do not know any good tools but as last resort you could include some code in your application to check it, similar to the following:

__thread void* stack_start;
__thread long stack_max_size = 0L;

void check_stack_size() {
  // address of 'nowhere' approximates end of stack
  char nowhere;
  void* stack_end = (void*)&nowhere;
  // may want to double check stack grows downward on your platform
  long stack_size = (long)stack_start - (long)stack_end;
  // update max_stack_size for this thread
  if (stack_size > stack_max_size)
    stack_max_size = stack_size;
}

The check_stack_size() function would have to be called in some of the functions that are most deeply nested.

Then as last statement in the thread you could output stack_max_size to somewhere.

The stack_start variable would have to be initialized at start of your thread:

void thread_proc() {
  char nowhere;
  stack_start = (void*)&nowhere;
  // do stuff including calls to check_stack_size()
  // in deeply nested functions
  // output stack_max_size here
}

Here are two tools that measure (native pthreads) stack usage in Linux applications:

Valgrind

Usage:

valgrind --tool=drd --show-stack-usage=yes PROG

Valgrind is a stable and powerful tool, useful not only for measuring stack usage. It may not support all embedded CPU models though.

Stackusage

Usage:

stackusage PROG

Stackusage is a light-weight tool specifically designed for measuring thread stack usage which should be portable for most embedded Linux platforms equipped with glibc. It is likely not as well-tested or mature as Valgrind/drd at this point.

Full disclosure: I'm the author of Stackusage.

DGentry

Referencing Tobi's answer: You can use pthread_attr_getstackaddr to get the base of the stack at any time, if setting a variable at thread initialization is difficult. You can then get the address of an automatic variable in your own function to determine how deep the stack is at that moment.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!