简体   繁体   中英

How to find exact stack and heap memory used by a process in linux/ubuntu?

I have project written in C-language. I need to find out how much Stack(local variables,..) and Heap memory(allocated with malloc) this process is using. So that I can make a decision that whether a particular Microcontroller(currently my controller has 30KB RAM) meet my project's minimum RAM/Stack/Heap requirements or not.

I tried /proc/pid/smaps. But it is showing minimun 4kB stack even if the file contains only 2 local integer variables.(I think it's showing Page size or memory range).

top command output is not useful for this requirement.

Is there any tool to find out stack(with moderate accuracy in bytes) used by a process in realtime in the form of variables etc(or atleast maximum value reached in lifetime also fine).(with this later I need to setup CI job for finding these.)

Atleast I could find out heap using malloc wrapper API like below.(don't know how to find out deallocated memory in a easy way.)

Eg: void call_malloc(size_t n) { usedMem = usedMem + n; // global variable p= malloc(n); }

I found reasonable solution.

While compiling use -fstack-usage flag. Eg: gcc -g -fstack-usage filename.c -fstack-usage flag. Eg: gcc -g -fstack-usage filename.c

Use the same in CFLAGS in makefile. No need to run the executable. After compiling, the same file name with.su extension will be there in that folder. It can be opened using cat/vim/notepad etc.

For heap memory calculation, simply use valgrind.

PS: While digging more I found below answer. How to determine maximum stack usage in embedded system with gcc?

If you run your code with the very basic command

/usr/bin/time --verbose ${executable}

you will get the following type of output. If you focus on the " Maximum resident set size ", and consider the values for " Average stack size " and " Average total size " (ie stack + heap), would that address your needs?

Command being timed: "{your_executable}"
User time (seconds): 0.00
System time (seconds): 0.01
Percent of CPU this job got: 90%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.01
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 4032
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 385
Voluntary context switches: 5
Involuntary context switches: 84
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0

This is also discussed more expansively here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM