Home > Back-end >  print out the total usable memory available
print out the total usable memory available

Time:01-29

This is what I currently have but I'm doing it wrong. Can someone please explain how to format the output into GB? I have a total of 16GB of available ram and I'm getting an output of 62GB.

#include <stdio.h>
#include <sys/sysinfo.h>

int main(void) {
  struct sysinfo sys_info; // for system information
  sysinfo(&sys_info); // to get system information
  
  printf("Total usable memory size: %ldGB", sys_info.totalram / 1024 / 1024 / 1024);

  return 0;
}

CodePudding user response:

First note that sysinfo will actually already give you the size in kB (KiloBytes). That means that you actually divide by 1000.0 to get GB (GigaByte). Also I think you would want your output to be double precision.

I modified your code

#include <stdio.h>
#include <sys/sysinfo.h>

int main(void) {

  struct sysinfo sys_info; // for system information
  sysinfo(&sys_info); // to get system information
  // note: %.3f is double precision but I only need to display 3 decimal places
  printf("Total usable memory size       : %.3fGB", sys_info.totalram / 1000.0 / 1000.0 / 1000.0);


  return 0;
}

Don't be confused when you try to verify this using cat /proc/meminfo. This is actually displaying the total memory in KibiBytes. One KibiByte is 1.024 KiloByte. You can do the math and it will also end up in the same solution.

CodePudding user response:

I tried your code on my machine and it worked fine. Sometimes sys_info.totalram works weird in system with more than 4GB - 8GB memory. So, try to use it:

 int result = ((unsigned long)sys_info.totalram * sys_info.mem_unit) / 1024 / 1014 / 1014;

sys_info.totalram return the total of usable memory, so you've to multiply it by sys_info.mem_unit to get all real memory available. And also, try to cast the sys_info.totalram before use it.

  •  Tags:  
  • Related