Skip to content
Advertisement

Why do I get different results for finding the peak of memory usage?

In Linux, I am using /usr/bin/time -f %M tool (gnu-time) to get the peak of the memory used for a single process/program. But every time that I run this command, I get a different result.

  1. What’s the reason of this difference?
  2. How can I get the accurate value for the maximum memory consumed by a process?

p.s. I’ve already used other methods like the ones taking snapshots from the memory (like reading from /proc/pid), but as my program ends so fast, I don’t want anything with even very tiny sampling rate.

Advertisement

Answer

Any non-deterministic process may obviously result in different memory usage each time. For example, you will never be able to run a large program like Gimp or Chrome and get the same number twice, even if you do the same operation.

However, if you’re seeing changes in memory usage for a simple, highly deterministic process, you probably have Address Space Layout Randomization turned on.

Here’s an example foo.c:

int main() {
  return 0;
}

You can see it having different memory usage each time:

$ gcc foo.c -o foo

$ /usr/bin/time -f +%M ./foo
+1144
$ /usr/bin/time -f +%M ./foo
+1048
$ /usr/bin/time -f +%M ./foo
+1060

This is because ASLR is fully enabled:

$ cat /proc/sys/kernel/randomize_va_space
2

If you turn it off:

$ sudo tee /proc/sys/kernel/randomize_va_space <<< 0
0

You’ll get the same value:

$ /usr/bin/time -f +%M ./foo
+1144
$ /usr/bin/time -f +%M ./foo
+1144
$ /usr/bin/time -f +%M ./foo
+1144

But don’t forget to turn it back on for the added security:

sudo tee /proc/sys/kernel/randomize_va_space <<< 2
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement