6

I have written two C programmes

  1. one is using function pointer, and
  2. the other without function pointer.

Now i want to know the memory consumed by the two programmes , to see how memory can optimized.

1
  • Are you interested in total RSS, size of the executable code, amount of heap memory or the stack usage? It's possible compute any one value but you need to specify which you mean. In addition, RSS is increased in page size blocks (typically 4096 bytes) and if you're talking about one function pointer, the size difference is 8 bytes at max. Aug 27, 2021 at 12:11

4 Answers 4

7

If you are only interested in the memory used after the fact, then use GNU time:

command time -v myprogram

(the above uses the bash way of invoking the external time command rather than the bash builtin, your shell may vary).

Or, GNU memusage:

memusage -T ./myprogram

If you are interested in the memory used on an ongoing basis (i.e. during a long running process), one of the other answers is probably better. See also this related question: Memory usage command with syntax similar to the time command

5

It would depend on what kind of stats you want, but if you're writing a program in C running on Linux, you'd definitely better know about Valgrind.

Valgrind can, not only profile detailed memory usage of your program, but also detect memory access violations which are common in C and possibly very hard to debug.

For your profiling purpose, take a look at docs about specific analysis tools, especially memcheck and massif.

3

Here's the resident set size and virtual memory size of all sshd processes on one system:

ulric@qvp2:~$ ps -eo rss,vsz,args|grep sshd|grep -v grep
  448  55292 /usr/sbin/sshd -D
 5176 147460 sshd: ulric [priv]
 2776 149704 sshd: ulric@pts/3

Or perhaps easier:

ulric@qvp2:~$ ps aux|head -n 1&&ps aux|grep sshd|grep -v grep
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root     13221  0.0  0.0  55292   448 ?        Ss   Apr21   0:01 /usr/sbin/sshd -D
root     16046  0.0  0.5 147460  5176 ?        Ss   08:12   0:00 sshd: ulric [priv]
ulric    16187  0.0  0.2 149704  2776 ?        S    08:12   0:00 sshd: ulric@pts/3

See the ps manpage for more options.

-2

The easiest to just catch the heap pointers through sbrk(0), cast them as 64-bit unsigned integers, and compute the difference after the memory gets allocated.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .