<p>In Flex, I have an xml document such as the following:</p>

<pre><code>var xml:XML = &lt;root&gt;&lt;node&gt;value1&lt;/node&gt;&lt;node&gt;value2&lt;/node&gt;&lt;node&gt;value3&lt;/node&gt;&lt;/root&gt;
</code></pre>

<p>At runtime, I want to create a TextInput control for each node under root, and have the values bound to the values in the XML. As far as I can tell I can't use BindingUtils to bind to e4x nodes at runtime (please tell me if I'm wrong here!), so I'm trying to do this by hand:</p>

<pre><code>for each (var node:XML in xml.node)
{
    var textInput:TextInput = new TextInput();
    var handler:Function = function(event:Event):void 
    {
        node.setChildren(event.target.text);
    };
    textInput.text = node.text();
    textInput.addEventListener(Event.CHANGE, handler);
    this.addChild(pileHeightEditor);
}
</code></pre>

<p>My problem is that when the user edits one of the TextInputs, the node getting assigned to is always the last one encountered in the for loop. I am used to this pattern from C#, where each time an anonymous function is created, a "snapshot" of the values of the used values is taken, so "node" would be different in each handler function.</p>

<p>How do I "take a snapshot" of the current value of node to use in the handler? Or should I be using a different pattern in Flex?</p>

[{'answer_id': 64166, 'author': 'Lanzelot', 'author_id': 7381, 'author_profile': 'https://Stackoverflow.com/users/7381', 'pm_score': 10, 'selected': False, 'text': "<h2>Windows</h2>\n<p>Some of the above values are easily available from the appropriate Win32 API, I just list them here for completeness. Others, however, need to be obtained from the Performance Data Helper library (PDH), which is a bit &quot;unintuitive&quot; and takes a lot of painful trial and error to get to work. (At least it took me quite a while, perhaps I've been only a bit stupid...)</p>\n<p>Note: for clarity all error checking has been omitted from the following code. Do check the return codes...!</p>\n<ul>\n<li><p>Total Virtual Memory:</p>\n<pre><code>#include &quot;windows.h&quot;\n\nMEMORYSTATUSEX memInfo;\nmemInfo.dwLength = sizeof(MEMORYSTATUSEX);\nGlobalMemoryStatusEx(&amp;memInfo);\nDWORDLONG totalVirtualMem = memInfo.ullTotalPageFile;\n</code></pre>\n<p>Note: The name &quot;TotalPageFile&quot; is a bit misleading here. In reality this parameter gives the &quot;Virtual Memory Size&quot;, which is size of swap file plus installed RAM.</p>\n</li>\n<li><p>Virtual Memory currently used:</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code> DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;\n</code></pre>\n</li>\n<li><p>Virtual Memory currently used by current process:</p>\n<pre><code>#include &quot;windows.h&quot;\n#include &quot;psapi.h&quot;\n\nPROCESS_MEMORY_COUNTERS_EX pmc;\nGetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&amp;pmc, sizeof(pmc));\nSIZE_T virtualMemUsedByMe = pmc.PrivateUsage;\n</code></pre>\n</li>\n<li><p>Total Physical Memory (RAM):</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code>DWORDLONG totalPhysMem = memInfo.ullTotalPhys;\n</code></pre>\n</li>\n<li><p>Physical Memory currently used:</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code>DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;\n</code></pre>\n</li>\n<li><p>Physical Memory currently used by current process:</p>\n<p>Same code as in &quot;Virtual Memory currently used by current process&quot; and then</p>\n<pre><code>SIZE_T physMemUsedByMe = pmc.WorkingSetSize;\n</code></pre>\n</li>\n<li><p>CPU currently used:</p>\n<pre><code>#include &quot;TCHAR.h&quot;\n#include &quot;pdh.h&quot;\n\nstatic PDH_HQUERY cpuQuery;\nstatic PDH_HCOUNTER cpuTotal;\n\nvoid init(){\n    PdhOpenQuery(NULL, NULL, &amp;cpuQuery);\n    // You can also use L&quot;\\\\Processor(*)\\\\% Processor Time&quot; and get individual CPU values with PdhGetFormattedCounterArray()\n    PdhAddEnglishCounter(cpuQuery, L&quot;\\\\Processor(_Total)\\\\% Processor Time&quot;, NULL, &amp;cpuTotal);\n    PdhCollectQueryData(cpuQuery);\n}\n\ndouble getCurrentValue(){\n    PDH_FMT_COUNTERVALUE counterVal;\n\n    PdhCollectQueryData(cpuQuery);\n    PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &amp;counterVal);\n    return counterVal.doubleValue;\n}\n</code></pre>\n</li>\n<li><p>CPU currently used by current process:</p>\n<pre><code>#include &quot;windows.h&quot;\n\nstatic ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;\nstatic int numProcessors;\nstatic HANDLE self;\n\nvoid init(){\n    SYSTEM_INFO sysInfo;\n    FILETIME ftime, fsys, fuser;\n\n    GetSystemInfo(&amp;sysInfo);\n    numProcessors = sysInfo.dwNumberOfProcessors;\n\n    GetSystemTimeAsFileTime(&amp;ftime);\n    memcpy(&amp;lastCPU, &amp;ftime, sizeof(FILETIME));\n\n    self = GetCurrentProcess();\n    GetProcessTimes(self, &amp;ftime, &amp;ftime, &amp;fsys, &amp;fuser);\n    memcpy(&amp;lastSysCPU, &amp;fsys, sizeof(FILETIME));\n    memcpy(&amp;lastUserCPU, &amp;fuser, sizeof(FILETIME));\n}\n\ndouble getCurrentValue(){\n    FILETIME ftime, fsys, fuser;\n    ULARGE_INTEGER now, sys, user;\n    double percent;\n\n    GetSystemTimeAsFileTime(&amp;ftime);\n    memcpy(&amp;now, &amp;ftime, sizeof(FILETIME));\n\n    GetProcessTimes(self, &amp;ftime, &amp;ftime, &amp;fsys, &amp;fuser);\n    memcpy(&amp;sys, &amp;fsys, sizeof(FILETIME));\n    memcpy(&amp;user, &amp;fuser, sizeof(FILETIME));\n    percent = (sys.QuadPart - lastSysCPU.QuadPart) +\n        (user.QuadPart - lastUserCPU.QuadPart);\n    percent /= (now.QuadPart - lastCPU.QuadPart);\n    percent /= numProcessors;\n    lastCPU = now;\n    lastUserCPU = user;\n    lastSysCPU = sys;\n\n    return percent * 100;\n}\n</code></pre>\n</li>\n</ul>\n<hr />\n<h2>Linux</h2>\n<p>On Linux the choice that seemed obvious at first was to use the POSIX APIs like <code>getrusage()</code> etc. I spent some time trying to get this to work, but never got meaningful values. When I finally checked the kernel sources themselves, I found out that apparently these APIs are not yet completely implemented as of Linux kernel 2.6!?</p>\n<p>In the end I got all values via a combination of reading the pseudo-filesystem <code>/proc</code> and kernel calls.</p>\n<ul>\n<li><p>Total Virtual Memory:</p>\n<pre><code>#include &quot;sys/types.h&quot;\n#include &quot;sys/sysinfo.h&quot;\n\nstruct sysinfo memInfo;\n\nsysinfo (&amp;memInfo);\nlong long totalVirtualMem = memInfo.totalram;\n//Add other values in next statement to avoid int overflow on right hand side...\ntotalVirtualMem += memInfo.totalswap;\ntotalVirtualMem *= memInfo.mem_unit;\n</code></pre>\n</li>\n<li><p>Virtual Memory currently used:</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code>long long virtualMemUsed = memInfo.totalram - memInfo.freeram;\n//Add other values in next statement to avoid int overflow on right hand side...\nvirtualMemUsed += memInfo.totalswap - memInfo.freeswap;\nvirtualMemUsed *= memInfo.mem_unit;\n</code></pre>\n</li>\n<li><p>Virtual Memory currently used by current process:</p>\n<pre><code>#include &quot;stdlib.h&quot;\n#include &quot;stdio.h&quot;\n#include &quot;string.h&quot;\n\nint parseLine(char* line){\n    // This assumes that a digit will be found and the line ends in &quot; Kb&quot;.\n    int i = strlen(line);\n    const char* p = line;\n    while (*p &lt;'0' || *p &gt; '9') p++;\n    line[i-3] = '\\0';\n    i = atoi(p);\n    return i;\n}\n\nint getValue(){ //Note: this value is in KB!\n    FILE* file = fopen(&quot;/proc/self/status&quot;, &quot;r&quot;);\n    int result = -1;\n    char line[128];\n\n    while (fgets(line, 128, file) != NULL){\n        if (strncmp(line, &quot;VmSize:&quot;, 7) == 0){\n            result = parseLine(line);\n            break;\n        }\n    }\n    fclose(file);\n    return result;\n}\n</code></pre>\n</li>\n<li><p>Total Physical Memory (RAM):</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code>long long totalPhysMem = memInfo.totalram;\n//Multiply in next statement to avoid int overflow on right hand side...\ntotalPhysMem *= memInfo.mem_unit;\n</code></pre>\n</li>\n<li><p>Physical Memory currently used:</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code>long long physMemUsed = memInfo.totalram - memInfo.freeram;\n//Multiply in next statement to avoid int overflow on right hand side...\nphysMemUsed *= memInfo.mem_unit;\n</code></pre>\n</li>\n<li><p>Physical Memory currently used by current process:</p>\n<p>Change getValue() in &quot;Virtual Memory currently used by current process&quot; as follows:</p>\n<pre><code>int getValue(){ //Note: this value is in KB!\n    FILE* file = fopen(&quot;/proc/self/status&quot;, &quot;r&quot;);\n    int result = -1;\n    char line[128];\n\n    while (fgets(line, 128, file) != NULL){\n        if (strncmp(line, &quot;VmRSS:&quot;, 6) == 0){\n            result = parseLine(line);\n            break;\n        }\n    }\n    fclose(file);\n    return result;\n}\n</code></pre>\n</li>\n</ul>\n<p></p>\n<ul>\n<li><p>CPU currently used:</p>\n<pre><code>#include &quot;stdlib.h&quot;\n#include &quot;stdio.h&quot;\n#include &quot;string.h&quot;\n\nstatic unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;\n\nvoid init(){\n    FILE* file = fopen(&quot;/proc/stat&quot;, &quot;r&quot;);\n    fscanf(file, &quot;cpu %llu %llu %llu %llu&quot;, &amp;lastTotalUser, &amp;lastTotalUserLow,\n        &amp;lastTotalSys, &amp;lastTotalIdle);\n    fclose(file);\n}\n\ndouble getCurrentValue(){\n    double percent;\n    FILE* file;\n    unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total;\n\n    file = fopen(&quot;/proc/stat&quot;, &quot;r&quot;);\n    fscanf(file, &quot;cpu %llu %llu %llu %llu&quot;, &amp;totalUser, &amp;totalUserLow,\n        &amp;totalSys, &amp;totalIdle);\n    fclose(file);\n\n    if (totalUser &lt; lastTotalUser || totalUserLow &lt; lastTotalUserLow ||\n        totalSys &lt; lastTotalSys || totalIdle &lt; lastTotalIdle){\n        //Overflow detection. Just skip this value.\n        percent = -1.0;\n    }\n    else{\n        total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) +\n            (totalSys - lastTotalSys);\n        percent = total;\n        total += (totalIdle - lastTotalIdle);\n        percent /= total;\n        percent *= 100;\n    }\n\n    lastTotalUser = totalUser;\n    lastTotalUserLow = totalUserLow;\n    lastTotalSys = totalSys;\n    lastTotalIdle = totalIdle;\n\n    return percent;\n}\n</code></pre>\n</li>\n<li><p>CPU currently used by current process:</p>\n<pre><code>#include &quot;stdlib.h&quot;\n#include &quot;stdio.h&quot;\n#include &quot;string.h&quot;\n#include &quot;sys/times.h&quot;\n#include &quot;sys/vtimes.h&quot;\n\nstatic clock_t lastCPU, lastSysCPU, lastUserCPU;\nstatic int numProcessors;\n\nvoid init(){\n    FILE* file;\n    struct tms timeSample;\n    char line[128];\n\n    lastCPU = times(&amp;timeSample);\n    lastSysCPU = timeSample.tms_stime;\n    lastUserCPU = timeSample.tms_utime;\n\n    file = fopen(&quot;/proc/cpuinfo&quot;, &quot;r&quot;);\n    numProcessors = 0;\n    while(fgets(line, 128, file) != NULL){\n        if (strncmp(line, &quot;processor&quot;, 9) == 0) numProcessors++;\n    }\n    fclose(file);\n}\n\ndouble getCurrentValue(){\n    struct tms timeSample;\n    clock_t now;\n    double percent;\n\n    now = times(&amp;timeSample);\n    if (now &lt;= lastCPU || timeSample.tms_stime &lt; lastSysCPU ||\n        timeSample.tms_utime &lt; lastUserCPU){\n        //Overflow detection. Just skip this value.\n        percent = -1.0;\n    }\n    else{\n        percent = (timeSample.tms_stime - lastSysCPU) +\n            (timeSample.tms_utime - lastUserCPU);\n        percent /= (now - lastCPU);\n        percent /= numProcessors;\n        percent *= 100;\n    }\n    lastCPU = now;\n    lastSysCPU = timeSample.tms_stime;\n    lastUserCPU = timeSample.tms_utime;\n\n    return percent;\n}\n</code></pre>\n</li>\n</ul>\n<hr />\n<h2>TODO: Other Platforms</h2>\n<p>I would assume, that some of the Linux code also works for the Unixes, except for the parts that read the /proc pseudo-filesystem. Perhaps on Unix these parts can be replaced by <code>getrusage()</code> and similar functions?</p>\n"}, {'answer_id': 64422, 'author': 'Martin Del Vecchio', 'author_id': 5397, 'author_profile': 'https://Stackoverflow.com/users/5397', 'pm_score': 6, 'selected': False, 'text': '<h1>Linux</h1>\n\n<p>In Linux, this information is available in the /proc file system.  I\'m not a big fan of the text file format used, as each Linux distribution seems to customize at least one important file.  A quick look as the source to \'ps\' reveals the mess.</p>\n\n<p>But here is where to find the information you seek:</p>\n\n<p><strong>/proc/meminfo</strong> contains the majority of the system-wide information you seek.  Here it looks like on my system; I think you are interested in <strong>MemTotal</strong>, <strong>MemFree</strong>, <strong>SwapTotal</strong>, and <strong>SwapFree</strong>:</p>\n\n<pre><code>Anderson cxc # more /proc/meminfo\nMemTotal:      4083948 kB\nMemFree:       2198520 kB\nBuffers:         82080 kB\nCached:        1141460 kB\nSwapCached:          0 kB\nActive:        1137960 kB\nInactive:       608588 kB\nHighTotal:     3276672 kB\nHighFree:      1607744 kB\nLowTotal:       807276 kB\nLowFree:        590776 kB\nSwapTotal:     2096440 kB\nSwapFree:      2096440 kB\nDirty:              32 kB\nWriteback:           0 kB\nAnonPages:      523252 kB\nMapped:          93560 kB\nSlab:            52880 kB\nSReclaimable:    24652 kB\nSUnreclaim:      28228 kB\nPageTables:       2284 kB\nNFS_Unstable:        0 kB\nBounce:              0 kB\nCommitLimit:   4138412 kB\nCommitted_AS:  1845072 kB\nVmallocTotal:   118776 kB\nVmallocUsed:      3964 kB\nVmallocChunk:   112860 kB\nHugePages_Total:     0\nHugePages_Free:      0\nHugePages_Rsvd:      0\nHugepagesize:     2048 kB\n</code></pre>\n\n<p>For CPU utilization, you have to do a little work.  Linux makes available overall CPU utilization since system start; this probably isn\'t what you are interested in.  If you want to know what the CPU utilization was for the last second, or 10 seconds, then you need to query the information and calculate it yourself.</p>\n\n<p>The information is available in <strong>/proc/stat</strong>, which is documented pretty well at <a href="http://www.linuxhowtos.org/System/procstat.htm" rel="noreferrer">http://www.linuxhowtos.org/System/procstat.htm</a>; here is what it looks like on my 4-core box:</p>\n\n<pre><code>Anderson cxc #  more /proc/stat\ncpu  2329889 0 2364567 1063530460 9034 9463 96111 0\ncpu0 572526 0 636532 265864398 2928 1621 6899 0\ncpu1 590441 0 531079 265949732 4763 351 8522 0\ncpu2 562983 0 645163 265796890 682 7490 71650 0\ncpu3 603938 0 551790 265919440 660 0 9040 0\nintr 37124247\nctxt 50795173133\nbtime 1218807985\nprocesses 116889\nprocs_running 1\nprocs_blocked 0\n</code></pre>\n\n<p>First, you need to determine how many CPUs (or processors, or processing cores) are available in the system.  To do this, count the number of \'cpuN\' entries, where N starts at 0 and increments.  Don\'t count the \'cpu\' line, which is a combination of the cpuN lines.  In my example, you can see cpu0 through cpu3, for a total of 4 processors.  From now on, you can ignore cpu0..cpu3, and focus only on the \'cpu\' line.</p>\n\n<p>Next, you need to know that the fourth number in these lines is a measure of idle time, and thus the fourth number on the \'cpu\' line is the total idle time for all processors since boot time.  This time is measured in Linux "jiffies", which are 1/100 of a second each. </p>\n\n<p>But you don\'t care about the total idle time; you care about the idle time in a given period, e.g., the last second.  Do calculate that, you need to read this file twice, 1 second apart.Then you can do a diff of the fourth value of the line.  For example, if you take a sample and get:</p>\n\n<pre><code>cpu  2330047 0 2365006 1063853632 9035 9463 96114 0\n</code></pre>\n\n<p>Then one second later you get this sample:</p>\n\n<pre><code>cpu  2330047 0 2365007 1063854028 9035 9463 96114 0\n</code></pre>\n\n<p>Subtract the two numbers, and you get a diff of 396, which means that your CPU had been idle for 3.96 seconds out of the last 1.00 second.  The trick, of course, is that you need to divide by the number of processors.  3.96 / 4 = 0.99, and there is your idle percentage; 99% idle, and 1% busy.</p>\n\n<p>In my code, I have a ring buffer of 360 entries, and I read this file every second.  That lets me quickly calculate the CPU utilization for 1 second, 10 seconds, etc., all the way up to 1 hour.</p>\n\n<p>For the process-specific information, you have to look in <strong>/proc/pid</strong>; if you don\'t care abut your pid, you can look in /proc/self.</p>\n\n<p>CPU used by your process is available in <strong>/proc/self/stat</strong>.  This is an odd-looking file consisting of a single line; for example:</p>\n\n<pre><code>19340 (whatever) S 19115 19115 3084 34816 19115 4202752 118200 607 0 0 770 384 2\n 7 20 0 77 0 266764385 692477952 105074 4294967295 134512640 146462952 321468364\n8 3214683328 4294960144 0 2147221247 268439552 1276 4294967295 0 0 17 0 0 0 0\n</code></pre>\n\n<p>The important data here are the 13th and 14th tokens (0 and 770 here).  The 13th token is the number of jiffies that the process has executed in user mode, and the 14th is the number of jiffies that the process has executed in kernel mode.  Add the two together, and you have its total CPU utilization.</p>\n\n<p>Again, you will have to sample this file periodically, and calculate the diff, in order to determine the process\'s CPU usage over time.  </p>\n\n<p><strong>Edit:</strong>  remember that when you calculate your process\'s CPU utilization, you have to take into account 1) the number of threads in your process, and 2) the number of processors in the system.  For example, if your single-threaded process is using only 25% of the CPU, that could be good or bad.  Good on a single-processor system, but bad on a 4-processor system; this means that your process is running constantly, and using 100% of the CPU cycles available to it.</p>\n\n<p>For the process-specific memory information, you ahve to look at /proc/self/status, which looks like this:</p>\n\n<pre><code>Name:   whatever\nState:  S (sleeping)\nTgid:   19340\nPid:    19340\nPPid:   19115\nTracerPid:      0\nUid:    0       0       0       0\nGid:    0       0       0       0\nFDSize: 256\nGroups: 0 1 2 3 4 6 10 11 20 26 27\nVmPeak:   676252 kB\nVmSize:   651352 kB\nVmLck:         0 kB\nVmHWM:    420300 kB\nVmRSS:    420296 kB\nVmData:   581028 kB\nVmStk:       112 kB\nVmExe:     11672 kB\nVmLib:     76608 kB\nVmPTE:      1244 kB\nThreads:        77\nSigQ:   0/36864\nSigPnd: 0000000000000000\nShdPnd: 0000000000000000\nSigBlk: fffffffe7ffbfeff\nSigIgn: 0000000010001000\nSigCgt: 20000001800004fc\nCapInh: 0000000000000000\nCapPrm: 00000000ffffffff\nCapEff: 00000000fffffeff\nCpus_allowed:   0f\nMems_allowed:   1\nvoluntary_ctxt_switches:        6518\nnonvoluntary_ctxt_switches:     6598\n</code></pre>\n\n<p>The entries that start with \'Vm\' are the interesting ones:</p>\n\n<ul>\n<li><strong>VmPeak</strong> is the maximum virtual memory space used by the process, in kB (1024 bytes).</li>\n<li><strong>VmSize</strong> is the current virtual memory space used by the process, in kB.  In my example, it\'s pretty large:  651,352 kB, or about 636 megabytes.</li>\n<li><strong>VmRss</strong> is the amount of memory that have been mapped into the process\' address space, or its resident set size.  This is substantially smaller (420,296 kB, or about 410 megabytes).  The difference:  my program has mapped 636 MB via mmap(), but has only accessed 410 MB of it, and thus only 410 MB of pages have been assigned to it.</li>\n</ul>\n\n<p>The only item I\'m not sure about is <strong>Swapspace currently used by my process</strong>.  I don\'t know if this is available.</p>\n'}, {'answer_id': 1911863, 'author': 'Michael Taylor', 'author_id': 172534, 'author_profile': 'https://Stackoverflow.com/users/172534', 'pm_score': 7, 'selected': False, 'text': "<h1>Mac OS X</h1>\n<h2>Total Virtual Memory</h2>\n<p>This one is tricky on Mac OS X because it doesn't use a preset swap partition or file like Linux. Here's an entry from Apple's documentation:</p>\n<blockquote>\n<p><strong>Note:</strong> Unlike most Unix-based operating systems, Mac OS X does not use a preallocated swap partition for virtual memory. Instead, it uses all of the available space on the machine’s boot partition.</p>\n</blockquote>\n<p>So, if you want to know how much virtual memory is still available, you need to get the size of the root partition. You can do that like this:</p>\n<pre><code>struct statfs stats;\nif (0 == statfs(&quot;/&quot;, &amp;stats))\n{\n    myFreeSwap = (uint64_t)stats.f_bsize * stats.f_bfree;\n}\n</code></pre>\n<h2>Total Virtual Currently Used</h2>\n<p>Calling systcl with the &quot;vm.swapusage&quot; key provides interesting information about swap usage:</p>\n<pre><code>sysctl -n vm.swapusage\nvm.swapusage: total = 3072.00M  used = 2511.78M  free = 560.22M  (encrypted)\n</code></pre>\n<p>Not that the total swap usage displayed here can change if more swap is needed as explained in the section above. So the total is actually the <em>current</em> swap total. In C++, this data can be queried this way:</p>\n<pre><code>xsw_usage vmusage = {0};\nsize_t size = sizeof(vmusage);\nif( sysctlbyname(&quot;vm.swapusage&quot;, &amp;vmusage, &amp;size, NULL, 0)!=0 )\n{\n   perror( &quot;unable to get swap usage by calling sysctlbyname(\\&quot;vm.swapusage\\&quot;,...)&quot; );\n}\n</code></pre>\n<p>Note that the &quot;xsw_usage&quot;, declared in sysctl.h, seems not documented and I suspect there there is a more portable way of accessing these values.</p>\n<h2>Virtual Memory Currently Used by my Process</h2>\n<p>You can get statistics about your current process using the <code>task_info</code> function. That includes the current resident size of your process and the current virtual size.</p>\n<pre><code>#include&lt;mach/mach.h&gt;\n\nstruct task_basic_info t_info;\nmach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;\n\nif (KERN_SUCCESS != task_info(mach_task_self(),\n                              TASK_BASIC_INFO, (task_info_t)&amp;t_info,\n                              &amp;t_info_count))\n{\n    return -1;\n}\n// resident size is in t_info.resident_size;\n// virtual size is in t_info.virtual_size;\n</code></pre>\n<h2>Total RAM available</h2>\n<p>The amount of physical RAM available in your system is available using the <code>sysctl</code> system function like this:</p>\n<pre><code>#include &lt;sys/types.h&gt;\n#include &lt;sys/sysctl.h&gt;\n...\nint mib[2];\nint64_t physical_memory;\nmib[0] = CTL_HW;\nmib[1] = HW_MEMSIZE;\nlength = sizeof(int64_t);\nsysctl(mib, 2, &amp;physical_memory, &amp;length, NULL, 0);\n</code></pre>\n<h2>RAM Currently Used</h2>\n<p>You can get general memory statistics from the <code>host_statistics</code> system function.</p>\n<pre><code>#include &lt;mach/vm_statistics.h&gt;\n#include &lt;mach/mach_types.h&gt;\n#include &lt;mach/mach_init.h&gt;\n#include &lt;mach/mach_host.h&gt;\n\nint main(int argc, const char * argv[]) {\n    vm_size_t page_size;\n    mach_port_t mach_port;\n    mach_msg_type_number_t count;\n    vm_statistics64_data_t vm_stats;\n\n    mach_port = mach_host_self();\n    count = sizeof(vm_stats) / sizeof(natural_t);\n    if (KERN_SUCCESS == host_page_size(mach_port, &amp;page_size) &amp;&amp;\n        KERN_SUCCESS == host_statistics64(mach_port, HOST_VM_INFO,\n                                        (host_info64_t)&amp;vm_stats, &amp;count))\n    {\n        long long free_memory = (int64_t)vm_stats.free_count * (int64_t)page_size;\n\n        long long used_memory = ((int64_t)vm_stats.active_count +\n                                 (int64_t)vm_stats.inactive_count +\n                                 (int64_t)vm_stats.wire_count) *  (int64_t)page_size;\n        printf(&quot;free memory: %lld\\nused memory: %lld\\n&quot;, free_memory, used_memory);\n    }\n\n    return 0;\n}\n</code></pre>\n<p>One thing to note here are that there are five types of memory pages in Mac\xa0OS\xa0X. They are as follows:</p>\n<ol>\n<li><strong>Wired</strong> pages that are locked in place and cannot be swapped out</li>\n<li><strong>Active</strong> pages that are loading into physical memory and would be relatively difficult to swap out</li>\n<li><strong>Inactive</strong> pages that are loaded into memory, but haven't been used recently and may not even be needed at all. These are potential candidates for swapping. This memory would probably need to be flushed.</li>\n<li><strong>Cached</strong> pages that have been some how cached that are likely to be easily reused. Cached memory probably would not require flushing. It is still possible for cached pages to be reactivated</li>\n<li><strong>Free</strong> pages that are completely free and ready to be used.</li>\n</ol>\n<p>It is good to note that just because Mac OS X may show very little actual free memory at times that it may not be a good indication of how much is ready to be used on short notice.</p>\n<h2>RAM Currently Used by my Process</h2>\n<p>See the &quot;Virtual Memory Currently Used by my Process&quot; above. The same code applies.</p>\n"}, {'answer_id': 13947253, 'author': 'Mohsen Zahraee', 'author_id': 1907986, 'author_profile': 'https://Stackoverflow.com/users/1907986', 'pm_score': 4, 'selected': False, 'text': '<p><strong>In Windows you can get CPU usage by the code below:</strong></p>\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;stdio.h&gt;\n\n//------------------------------------------------------------------------------------------------------------------\n// Prototype(s)...\n//------------------------------------------------------------------------------------------------------------------\nCHAR cpuusage(void);\n\n//-----------------------------------------------------\ntypedef BOOL ( __stdcall * pfnGetSystemTimes)( LPFILETIME lpIdleTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime );\nstatic pfnGetSystemTimes s_pfnGetSystemTimes = NULL;\n\nstatic HMODULE s_hKernel = NULL;\n//-----------------------------------------------------\nvoid GetSystemTimesAddress()\n{\n    if(s_hKernel == NULL)\n    {\n        s_hKernel = LoadLibrary(L&quot;Kernel32.dll&quot;);\n        if(s_hKernel != NULL)\n        {\n            s_pfnGetSystemTimes = (pfnGetSystemTimes)GetProcAddress(s_hKernel, &quot;GetSystemTimes&quot;);\n            if(s_pfnGetSystemTimes == NULL)\n            {\n                FreeLibrary(s_hKernel);\n                s_hKernel = NULL;\n            }\n        }\n    }\n}\n//----------------------------------------------------------------------------------------------------------------\n\n//----------------------------------------------------------------------------------------------------------------\n// cpuusage(void)\n// ==============\n// Return a CHAR value in the range 0 - 100 representing actual CPU usage in percent.\n//----------------------------------------------------------------------------------------------------------------\nCHAR cpuusage()\n{\n    FILETIME               ft_sys_idle;\n    FILETIME               ft_sys_kernel;\n    FILETIME               ft_sys_user;\n\n    ULARGE_INTEGER         ul_sys_idle;\n    ULARGE_INTEGER         ul_sys_kernel;\n    ULARGE_INTEGER         ul_sys_user;\n\n    static ULARGE_INTEGER     ul_sys_idle_old;\n    static ULARGE_INTEGER  ul_sys_kernel_old;\n    static ULARGE_INTEGER  ul_sys_user_old;\n\n    CHAR usage = 0;\n\n    // We cannot directly use GetSystemTimes in the C language\n    /* Add this line :: pfnGetSystemTimes */\n    s_pfnGetSystemTimes(&amp;ft_sys_idle,    /* System idle time */\n        &amp;ft_sys_kernel,  /* system kernel time */\n        &amp;ft_sys_user);   /* System user time */\n\n    CopyMemory(&amp;ul_sys_idle  , &amp;ft_sys_idle  , sizeof(FILETIME)); // Could been optimized away...\n    CopyMemory(&amp;ul_sys_kernel, &amp;ft_sys_kernel, sizeof(FILETIME)); // Could been optimized away...\n    CopyMemory(&amp;ul_sys_user  , &amp;ft_sys_user  , sizeof(FILETIME)); // Could been optimized away...\n\n    usage  =\n        (\n        (\n        (\n        (\n        (ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+\n        (ul_sys_user.QuadPart   - ul_sys_user_old.QuadPart)\n        )\n        -\n        (ul_sys_idle.QuadPart-ul_sys_idle_old.QuadPart)\n        )\n        *\n        (100)\n        )\n        /\n        (\n        (ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+\n        (ul_sys_user.QuadPart   - ul_sys_user_old.QuadPart)\n        )\n        );\n\n    ul_sys_idle_old.QuadPart   = ul_sys_idle.QuadPart;\n    ul_sys_user_old.QuadPart   = ul_sys_user.QuadPart;\n    ul_sys_kernel_old.QuadPart = ul_sys_kernel.QuadPart;\n\n    return usage;\n}\n\n\n//------------------------------------------------------------------------------------------------------------------\n// Entry point\n//------------------------------------------------------------------------------------------------------------------\nint main(void)\n{\n    int n;\n    GetSystemTimesAddress();\n    for(n=0; n&lt;20; n++)\n    {\n        printf(&quot;CPU Usage: %3d%%\\r&quot;, cpuusage());\n        Sleep(2000);\n    }\n    printf(&quot;\\n&quot;);\n    return 0;\n}\n</code></pre>\n'}, {'answer_id': 30452461, 'author': 'Boernii', 'author_id': 4894793, 'author_profile': 'https://Stackoverflow.com/users/4894793', 'pm_score': 2, 'selected': False, 'text': '<h1>QNX</h1>\n<p>Since this is like a &quot;wikipage of code&quot; I want to add some code from the QNX Knowledge base (note: this is not my work, but I checked it and it works fine on my system):</p>\n<p>How to get CPU usage in %: <a href="http://www.qnx.com/support/knowledgebase.html?id=50130000000P9b5" rel="nofollow noreferrer">http://www.qnx.com/support/knowledgebase.html?id=50130000000P9b5</a></p>\n<pre><code>#include &lt;atomic.h&gt;\n#include &lt;libc.h&gt;\n#include &lt;pthread.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;sys/iofunc.h&gt;\n#include &lt;sys/neutrino.h&gt;\n#include &lt;sys/resmgr.h&gt;\n#include &lt;sys/syspage.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;inttypes.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;sys/types.h&gt;\n#include &lt;sys/debug.h&gt;\n#include &lt;sys/procfs.h&gt;\n#include &lt;sys/syspage.h&gt;\n#include &lt;sys/neutrino.h&gt;\n#include &lt;sys/time.h&gt;\n#include &lt;time.h&gt;\n#include &lt;fcntl.h&gt;\n#include &lt;devctl.h&gt;\n#include &lt;errno.h&gt;\n\n#define MAX_CPUS 32\n\nstatic float Loads[MAX_CPUS];\nstatic _uint64 LastSutime[MAX_CPUS];\nstatic _uint64 LastNsec[MAX_CPUS];\nstatic int ProcFd = -1;\nstatic int NumCpus = 0;\n\n\nint find_ncpus(void) {\n    return NumCpus;\n}\n\nint get_cpu(int cpu) {\n    int ret;\n    ret = (int)Loads[ cpu % MAX_CPUS ];\n    ret = max(0,ret);\n    ret = min(100,ret);\n    return( ret );\n}\n\nstatic _uint64 nanoseconds( void ) {\n    _uint64 sec, usec;\n    struct timeval tval;\n    gettimeofday( &amp;tval, NULL );\n    sec = tval.tv_sec;\n    usec = tval.tv_usec;\n    return( ( ( sec * 1000000 ) + usec ) * 1000 );\n}\n\nint sample_cpus( void ) {\n    int i;\n    debug_thread_t debug_data;\n    _uint64 current_nsec, sutime_delta, time_delta;\n    memset( &amp;debug_data, 0, sizeof( debug_data ) );\n    \n    for( i=0; i&lt;NumCpus; i++ ) {\n        /* Get the sutime of the idle thread #i+1 */\n        debug_data.tid = i + 1;\n        devctl( ProcFd, DCMD_PROC_TIDSTATUS,\n        &amp;debug_data, sizeof( debug_data ), NULL );\n        /* Get the current time */\n        current_nsec = nanoseconds();\n        /* Get the deltas between now and the last samples */\n        sutime_delta = debug_data.sutime - LastSutime[i];\n        time_delta = current_nsec - LastNsec[i];\n        /* Figure out the load */\n        Loads[i] = 100.0 - ( (float)( sutime_delta * 100 ) / (float)time_delta );\n        /* Flat out strange rounding issues. */\n        if( Loads[i] &lt; 0 ) {\n            Loads[i] = 0;\n        }\n        /* Keep these for reference in the next cycle */\n        LastNsec[i] = current_nsec;\n        LastSutime[i] = debug_data.sutime;\n    }\n    return EOK;\n}\n\nint init_cpu( void ) {\n    int i;\n    debug_thread_t debug_data;\n    memset( &amp;debug_data, 0, sizeof( debug_data ) );\n/* Open a connection to proc to talk over.*/\n    ProcFd = open( &quot;/proc/1/as&quot;, O_RDONLY );\n    if( ProcFd == -1 ) {\n        fprintf( stderr, &quot;pload: Unable to access procnto: %s\\n&quot;,strerror( errno ) );\n        fflush( stderr );\n        return -1;\n    }\n    i = fcntl(ProcFd,F_GETFD);\n    if(i != -1){\n        i |= FD_CLOEXEC;\n        if(fcntl(ProcFd,F_SETFD,i) != -1){\n            /* Grab this value */\n            NumCpus = _syspage_ptr-&gt;num_cpu;\n            /* Get a starting point for the comparisons */\n            for( i=0; i&lt;NumCpus; i++ ) {\n                /*\n                * the sutime of idle thread is how much\n                * time that thread has been using, we can compare this\n                * against how much time has passed to get an idea of the\n                * load on the system.\n                */\n                debug_data.tid = i + 1;\n                devctl( ProcFd, DCMD_PROC_TIDSTATUS, &amp;debug_data, sizeof( debug_data ), NULL );\n                LastSutime[i] = debug_data.sutime;\n                LastNsec[i] = nanoseconds();\n            }\n            return(EOK);\n        }\n    }\n    close(ProcFd);\n    return(-1);\n}\n\nvoid close_cpu(void){\n    if(ProcFd != -1){\n        close(ProcFd);\n        ProcFd = -1;\n    }\n}\n\nint main(int argc, char* argv[]){\n    int i,j;\n    init_cpu();\n    printf(&quot;System has: %d CPUs\\n&quot;, NumCpus);\n    for(i=0; i&lt;20; i++) {\n        sample_cpus();\n        for(j=0; j&lt;NumCpus;j++)\n        printf(&quot;CPU #%d: %f\\n&quot;, j, Loads[j]);\n        sleep(1);\n    }\n    close_cpu();\n}\n</code></pre>\n<p>How to get the free (!) memory: <a href="http://www.qnx.com/support/knowledgebase.html?id=50130000000mlbx" rel="nofollow noreferrer">http://www.qnx.com/support/knowledgebase.html?id=50130000000mlbx</a></p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;errno.h&gt;\n#include &lt;err.h&gt;\n#include &lt;sys/stat.h&gt;\n#include &lt;sys/types.h&gt;\n\nint main( int argc, char *argv[] ){\n    struct stat statbuf;\n    paddr_t freemem;\n    stat( &quot;/proc&quot;, &amp;statbuf );\n    freemem = (paddr_t)statbuf.st_size;\n    printf( &quot;Free memory: %d bytes\\n&quot;, freemem );\n    printf( &quot;Free memory: %d KB\\n&quot;, freemem / 1024 );\n    printf( &quot;Free memory: %d MB\\n&quot;, freemem / ( 1024 * 1024 ) );\n    return 0;\n} \n</code></pre>\n'}, {'answer_id': 31464645, 'author': 'Mark Lakata', 'author_id': 364818, 'author_profile': 'https://Stackoverflow.com/users/364818', 'pm_score': 4, 'selected': False, 'text': '<h1>Linux</h1>\n\n<p>A portable way of reading memory and load numbers is the <a href="http://man7.org/linux/man-pages/man2/sysinfo.2.html" rel="noreferrer"><code>sysinfo</code> call</a></p>\n\n<h2>Usage</h2>\n\n<pre><code>   #include &lt;sys/sysinfo.h&gt;\n\n   int sysinfo(struct sysinfo *info);\n</code></pre>\n\n<h2>DESCRIPTION</h2>\n\n<pre><code>   Until Linux 2.3.16, sysinfo() used to return information in the\n   following structure:\n\n       struct sysinfo {\n           long uptime;             /* Seconds since boot */\n           unsigned long loads[3];  /* 1, 5, and 15 minute load averages */\n           unsigned long totalram;  /* Total usable main memory size */\n           unsigned long freeram;   /* Available memory size */\n           unsigned long sharedram; /* Amount of shared memory */\n           unsigned long bufferram; /* Memory used by buffers */\n           unsigned long totalswap; /* Total swap space size */\n           unsigned long freeswap;  /* swap space still available */\n           unsigned short procs;    /* Number of current processes */\n           char _f[22];             /* Pads structure to 64 bytes */\n       };\n\n   and the sizes were given in bytes.\n\n   Since Linux 2.3.23 (i386), 2.3.48 (all architectures) the structure\n   is:\n\n       struct sysinfo {\n           long uptime;             /* Seconds since boot */\n           unsigned long loads[3];  /* 1, 5, and 15 minute load averages */\n           unsigned long totalram;  /* Total usable main memory size */\n           unsigned long freeram;   /* Available memory size */\n           unsigned long sharedram; /* Amount of shared memory */\n           unsigned long bufferram; /* Memory used by buffers */\n           unsigned long totalswap; /* Total swap space size */\n           unsigned long freeswap;  /* swap space still available */\n           unsigned short procs;    /* Number of current processes */\n           unsigned long totalhigh; /* Total high memory size */\n           unsigned long freehigh;  /* Available high memory size */\n           unsigned int mem_unit;   /* Memory unit size in bytes */\n           char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding to 64 bytes */\n       };\n\n   and the sizes are given as multiples of mem_unit bytes.\n</code></pre>\n'}, {'answer_id': 40268513, 'author': 'Salman Ghaffar', 'author_id': 7037557, 'author_profile': 'https://Stackoverflow.com/users/7037557', 'pm_score': 0, 'selected': False, 'text': '<p>I used this following code in my C++ project and it worked fine:</p>\n\n<pre><code>static HANDLE self;\nstatic int numProcessors;\nSYSTEM_INFO sysInfo;\n\ndouble percent;\n\nnumProcessors = sysInfo.dwNumberOfProcessors;\n\n//Getting system times information\nFILETIME SysidleTime;\nFILETIME SyskernelTime; \nFILETIME SysuserTime; \nULARGE_INTEGER SyskernelTimeInt, SysuserTimeInt;\nGetSystemTimes(&amp;SysidleTime, &amp;SyskernelTime, &amp;SysuserTime);\nmemcpy(&amp;SyskernelTimeInt, &amp;SyskernelTime, sizeof(FILETIME));\nmemcpy(&amp;SysuserTimeInt, &amp;SysuserTime, sizeof(FILETIME));\n__int64 denomenator = SysuserTimeInt.QuadPart + SyskernelTimeInt.QuadPart;  \n\n//Getting process times information\nFILETIME ProccreationTime, ProcexitTime, ProcKernelTime, ProcUserTime;\nULARGE_INTEGER ProccreationTimeInt, ProcexitTimeInt, ProcKernelTimeInt, ProcUserTimeInt;\nGetProcessTimes(self, &amp;ProccreationTime, &amp;ProcexitTime, &amp;ProcKernelTime, &amp;ProcUserTime);\nmemcpy(&amp;ProcKernelTimeInt, &amp;ProcKernelTime, sizeof(FILETIME));\nmemcpy(&amp;ProcUserTimeInt, &amp;ProcUserTime, sizeof(FILETIME));\n__int64 numerator = ProcUserTimeInt.QuadPart + ProcKernelTimeInt.QuadPart;\n//QuadPart represents a 64-bit signed integer (ULARGE_INTEGER)\n\npercent = 100*(numerator/denomenator);\n</code></pre>\n'}, {'answer_id': 42925322, 'author': 'Steven Warner', 'author_id': 4721690, 'author_profile': 'https://Stackoverflow.com/users/4721690', 'pm_score': 2, 'selected': False, 'text': '<h3>For Linux</h3>\n<p>You can also use /proc/self/statm to get a single line of numbers containing key process memory information which is a faster thing to process than going through a long list of reported information as you get from proc/self/status</p>\n<p>See <em><a href="http://man7.org/linux/man-pages/man5/proc.5.html" rel="nofollow noreferrer">proc(5)</a></em></p>\n<pre class="lang-none prettyprint-override"><code>/proc/[pid]/statm\n\n    Provides information about memory usage, measured in pages.\n    The columns are:\n\n        size       (1) total program size\n                   (same as VmSize in /proc/[pid]/status)\n        resident   (2) resident set size\n                   (same as VmRSS in /proc/[pid]/status)\n        shared     (3) number of resident shared pages (i.e., backed by a file)\n                   (same as RssFile+RssShmem in /proc/[pid]/status)\n        text       (4) text (code)\n        lib        (5) library (unused since Linux 2.6; always 0)\n        data       (6) data + stack\n        dt         (7) dirty pages (unused since Linux 2.6; always 0)\n</code></pre>\n'}, {'answer_id': 49996245, 'author': 'souch', 'author_id': 4964856, 'author_profile': 'https://Stackoverflow.com/users/4964856', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Mac OS X - CPU</strong></p>\n<p>Overall CPU usage:</p>\n<p>From <em><a href="https://stackoverflow.com/questions/8736713/retrieve-system-information-on-macos-x">Retrieve system information on Mac OS X</a></em>:</p>\n<pre><code>#include &lt;mach/mach_init.h&gt;\n#include &lt;mach/mach_error.h&gt;\n#include &lt;mach/mach_host.h&gt;\n#include &lt;mach/vm_map.h&gt;\n\nstatic unsigned long long _previousTotalTicks = 0;\nstatic unsigned long long _previousIdleTicks = 0;\n\n// Returns 1.0f for &quot;CPU fully pinned&quot;, 0.0f for &quot;CPU idle&quot;, or somewhere in between\n// You\'ll need to call this at regular intervals, since it measures the load between\n// the previous call and the current one.\nfloat GetCPULoad()\n{\n   host_cpu_load_info_data_t cpuinfo;\n   mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;\n   if (host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&amp;cpuinfo, &amp;count) == KERN_SUCCESS)\n   {\n      unsigned long long totalTicks = 0;\n      for(int i=0; i&lt;CPU_STATE_MAX; i++) totalTicks += cpuinfo.cpu_ticks[i];\n      return CalculateCPULoad(cpuinfo.cpu_ticks[CPU_STATE_IDLE], totalTicks);\n   }\n   else return -1.0f;\n}\n\nfloat CalculateCPULoad(unsigned long long idleTicks, unsigned long long totalTicks)\n{\n  unsigned long long totalTicksSinceLastTime = totalTicks-_previousTotalTicks;\n  unsigned long long idleTicksSinceLastTime  = idleTicks-_previousIdleTicks;\n  float ret = 1.0f-((totalTicksSinceLastTime &gt; 0) ? ((float)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0);\n  _previousTotalTicks = totalTicks;\n  _previousIdleTicks  = idleTicks;\n  return ret;\n}\n</code></pre>\n'}, {'answer_id': 65270655, 'author': 'Marisa Kirisame', 'author_id': 7984460, 'author_profile': 'https://Stackoverflow.com/users/7984460', 'pm_score': 0, 'selected': False, 'text': '<p>On Linux, you cannot/should not get &quot;Total Available Physical Memory&quot; with SysInfo\'s freeram or by doing some arithmetic on totalram.</p>\n<p>The recommended way to do this is by reading proc/meminfo, quoting <em><a href="https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773" rel="nofollow noreferrer">kernel/git/torvalds/linux.git, <em>/proc/meminfo: provide estimated available memory</em></a></em>:</p>\n<blockquote>\n<p>Many load balancing and workload placing programs check /proc/meminfo to\nestimate how much free memory is available.  They generally do this by\nadding up &quot;free&quot; and &quot;cached&quot;, which was fine ten years ago, but is\npretty much guaranteed to be wrong today.</p>\n</blockquote>\n<blockquote>\n<p>It is more convenient to provide such an estimate in /proc/meminfo. If things change in the future, we only have to change it in one place.</p>\n</blockquote>\n<p>One way to do it is as <em><a href="https://stackoverflow.com/questions/349889/how-do-you-determine-the-amount-of-linux-system-ram-in-c/350039#350039">Adam Rosenfield\'s answer to <em>How do you determine the amount of Linux system RAM in C++?</em></a></em> suggest: read the file, and use fscanf to grab the line (but instead of going for MemTotal, go for MemAvailable)</p>\n<p>Likewise, if you want to get the total amount of physical memory used, depending on what you mean by &quot;use&quot;, you might not want to subtract freeram from totalram, but subtract memavailable from memtotal to get what top or htop tells you.</p>\n'}]
['https://Stackoverflow.com/questions/63181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6448/']