The malloc
and free
calls are more than trivial wrappers around sbrk
and mmap
system calls. This makes getrusage
return something that is not in line with calls to malloc
and free
. Any non-trivial implementation of these functions will manage a free-list inside the process itself, before thinking of returning anything to the system.
The program calls free
(or delete
for that matter), and the memory is not immediately returned to the operating system (maybe never). The free
-ed memory can be reused by the task, if it calls malloc
, but not by other processes. This makes getrusage
correct from the OS perspective, but not correct from the program perspective.
On Linux you can use mallinfo()
#include <malloc.h>
#include <cinttypes>
std::size_t memsize()
{
auto data = mallinfo();
return data.arena - data.fordblks + data.hblkhd;
}
Here, memsize()
will return the number of bytes allocated from program's perspective. It takes into account the various allocation techniques, such as sbrk
and mmap
, and considers rounding up and overhead as part of the allocated memory of malloc()
(and new
).
With OSX things are not so bright. You can have a look into the source code of apple's malloc(), and specifically at mstats
, which states in the comment:
/*
* A Glibc-like mstats() interface.
*
* Note that this interface really isn't very good, as it doesn't understand
* that we may have multiple allocators running at once. We just massage
* the result from malloc_zone_statistics in any case.
*/
This does not look very promising and:
#include <malloc/malloc.h>
#include <cinttypes>
std::size_t memsize()
{
auto data = mstats();
return data.bytes_used;
}
Does not look very good, according to my experiments. But it may be better than nothing, or just relying on getrusage
. I think you are out of luck on OSX, unless someone can correct me.