How to find out the amount of free physical memory

2019-08-05 12:42发布

Assume I want to cache certain calculations, but provoking syncing it out to disk would incur an I/O penalty that would more than defy the whole purpose of caching.

This means, I need to be able find out, how much physical RAM is left (including cached memory, assuming I can push that out and allowing for some slack should buffering increase). I looked into /proc/meminfo and know how to read it out. I am not so sure how to combine the numbers to get what i want though. Code not necessary, once i know what I need I can code it myself.

I will not have root on the box it needs to run at, but it should be reasonably quiet otherwise. No large amount of disk I/O, no other processes claiming a lot of mem in a burst. The OS is a rather recent linux with overcommitting turned on. This will need to work without triggering the OOM killer obviously.

The Numbers don't need to be exact down to the megabyte, I assume that it'll be roughly in the 1 to 7 gib range depending on the box but getting close to about 100 mb would be great.

It'd definitely be preferable if the estimate were to err on the smallish side.

3条回答
贼婆χ
2楼-- · 2019-08-05 12:45

Unices have the standard sysconf() function (OpenGroups man page, Linux man page).

Using this function, you can get the total physical memory:

unsigned long long ps = sysconf(_SC_PAGESIZE);
unsigned long long pn = sysconf(_SC_AVPHYS_PAGES);
unsigned long long availMem = ps * pn;
查看更多
ゆ 、 Hurt°
3楼-- · 2019-08-05 13:01

As an alternative to the answer of H2CO3, you can read from /proc/meminfo.

查看更多
劫难
4楼-- · 2019-08-05 13:03

For me, statfs worked well.

#include <sys/vfs.h>

struct statfs buf;
size_t available_mem;
if ( statfs( "/", &buf ) == -1 ) 
    available_mem = 0;
else 
    available_mem = buf.f_bsize * buf.f_bfree;
查看更多
登录 后发表回答