Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically get amount of RAM installed on OS X

I'm working on a machine that has 8 gigs of memory installed and I'm trying to programmatically determine how much memory is installed in the machine. I've already attempted using sysctlbyname() to get the amount of memory installed, however it seems to be limited to returning a signed 32 bit integer.

uint64_t total = 0;
size_t size = sizeof(total);
if( !sysctlbyname("hw.physmem", &total, &size, NULL, 0) )
     m_totalMemory = total;

The above code, no matter what type is passed to sysctlbyname, always returns 2147483648 in the total variable. I've been searching through IOKit and IORegistryExplorer for another route of determining installed memory, but have come up with nothing so far. I've found IODeviceTree:/memory in IORegistryExplorer, but there's no field in there for size. I'm not finding anything anywhere else in the IO Registry either. Is there a way to access this information via IOKit, or a way to make sysctlbyname return more than a 32-bit signed integer?

like image 816
Grant Limberg Avatar asked Sep 08 '09 22:09

Grant Limberg


2 Answers

You can use sysctl() and query HW_MEMSIZE.This returns the memory size as a 64-bit integer, instead of the default 32-bit integer.

The man page gives the details.

like image 176
David Crawshaw Avatar answered Nov 11 '22 08:11

David Crawshaw


The easy way:

[[NSProcessInfo processInfo] physicalMemory]
like image 28
Chuck Avatar answered Nov 11 '22 08:11

Chuck