Take the 2-minute tour ×
Ask Different is a question and answer site for power users of Apple hardware and software. It's 100% free, no registration required.

On Linux, I often use the free command to see the current amount of free and used memory in the system. For example:

$ free
             total       used       free     shared    buffers     cached
Mem:       7264256    1010952    6253304          0     371892     189088
-/+ buffers/cache:     449972    6814284
Swap:      8126456         28    8126428

It does not seem to exist when I enter "free" in Mac OS X's Terminal. Is there an alternative?

share|improve this question

16 Answers 16

up vote 35 down vote accepted

As @khedron says, you can see this info in Activity Monitor.

If you want it on the command line, here is a Python script that I wrote (or perhaps modified from someone else's, I can't remember, it's quite old now) to show you the Wired, Active, Inactive and Free memory amounts:

#!/usr/bin/python

import subprocess
import re

# Get process info
ps = subprocess.Popen(['ps', '-caxm', '-orss,comm'], stdout=subprocess.PIPE).communicate()[0]
vm = subprocess.Popen(['vm_stat'], stdout=subprocess.PIPE).communicate()[0]

# Iterate processes
processLines = ps.split('\n')
sep = re.compile('[\s]+')
rssTotal = 0 # kB
for row in range(1,len(processLines)):
    rowText = processLines[row].strip()
    rowElements = sep.split(rowText)
    try:
        rss = float(rowElements[0]) * 1024
    except:
        rss = 0 # ignore...
    rssTotal += rss

# Process vm_stat
vmLines = vm.split('\n')
sep = re.compile(':[\s]+')
vmStats = {}
for row in range(1,len(vmLines)-2):
    rowText = vmLines[row].strip()
    rowElements = sep.split(rowText)
    vmStats[(rowElements[0])] = int(rowElements[1].strip('\.')) * 4096

print 'Wired Memory:\t\t%d MB' % ( vmStats["Pages wired down"]/1024/1024 )
print 'Active Memory:\t\t%d MB' % ( vmStats["Pages active"]/1024/1024 )
print 'Inactive Memory:\t%d MB' % ( vmStats["Pages inactive"]/1024/1024 )
print 'Free Memory:\t\t%d MB' % ( vmStats["Pages free"]/1024/1024 )
print 'Real Mem Total (ps):\t%.3f MB' % ( rssTotal/1024/1024 )

As you can see, you can just call vm_stat from the command line, though it counts in 4kB pages, hence the script to convert to MB.

The script also counts up the "real memory" usage of all running processes for comparison (this won't match any specific value(s) from overall memory stats, because memory is a complex beast).


Here's an example of the output of the script on my system:

[user@host:~] % memReport.py
Wired Memory:           1381 MB
Active Memory:          3053 MB
Inactive Memory:        727 MB
Free Memory:            1619 MB
Real Mem Total (ps):    3402.828 MB

(very slightly adjusted to match the tab sizing on StackExchange ;)

share|improve this answer
    
what is the best way to use this script? –  idober Apr 22 '11 at 14:22
1  
not sure exactly what you mean... copy and paste it into a new file, save it somewhere (perhaps in /usr/local/bin), make it executable and run it? –  drfrogsplat May 9 '11 at 6:18
    
I think @idober was suggesting you include an example of running it and the output produced (e.g. a screen capture) –  AJ. Mar 29 '12 at 20:59
    
@AJ, ah ok, got it –  drfrogsplat Apr 5 '12 at 3:27

The command you need is "vm_stat" - similar to the traditional Unix tool "vmstat" but with a few MACH-specific differences. The man page is well written.

share|improve this answer
    
What are 'pages'? –  zhermes Nov 27 '13 at 19:13
2  
@zhermes - The smallest unit of memory usable by the system... in the case of x86 and PPC Macs, this is 4k. Pages free are the number of 4k units of memory free. –  RI Swamp Yankee Dec 1 '13 at 2:22
    
Pages are also 4K in iOS. –  smci Mar 10 at 5:35

There is a terminal command similar to free on Mac OS X... it is called top

For further information you can check out this Apple Support document.

Mac OS X: How to View Memory Usage With the "top" Utility

share|improve this answer
14  
Strictly speaking, "top" on OS X is rather more similar to the Linux "top" command, of course :) –  scottishwildcat Nov 11 '11 at 15:34
1  
better than top : htop –  nXqd Apr 20 '13 at 22:04
    
@nXqd htop: command not found –  Sazzad Tushar Khan Jan 22 at 19:42
    
You can increase/decrease the window size horizontally to see more/less columns. I can see these columns: PID COMMAND %CPU TIME #TH #WQ #PORT #MREGS RPRVT RSHRD RSIZE VPRVT VSIZE PGRP PPID STATE UID FAULTS COW MSGSENT MSGRECV SYSBSD SYSMACH CSW PAGEINS KPRVT KSHRD USER –  Sazzad Tushar Khan Jan 22 at 19:47
1  
@SazzadTusharKhan brew install htop if you do have brew installed –  nXqd Jan 22 at 21:08

It seems the reason it's slow is because 'top -l 1' would make all top output complete first, which takes a long time, then apply the next step in the piping sequence, so insert a 'head -n 10' segment in between to make it quick:

top -l 1 | head -n 10 | grep PhysMem

Also, for clarity, I like showing each mem-component on its line, so I added 9 spaces for alignment with 'PhysMem: ' in the sed replacement string:

top -l 1 | head -n 10 | grep PhysMem | sed 's/, /\n         /g'
share|improve this answer
1  
It's dog slow, it's much better to utilize vm_stat. –  m_gol Apr 14 '13 at 21:51
1  
Yes, querying top is significantly slower that calling vm_stat but the top extract is much less verbose and the unit is megabyte and not pages. To be even less verbose the line breaks can be removed and awk can be replaced by grep resulting in top -l 1 | grep ^PhysMem. –  Stefan Schmidt May 12 '13 at 16:39
#!/bin/bash

top -l 1 | grep PhysMem: | awk '{print $10}'

For Unix experts only:

top -l 1 | awk '/PhysMem:/ {print $10}'
share|improve this answer

Just taking the solution from @zack and adding inactive and speculative blocks.

#!/bin/bash

FREE_BLOCKS=$(vm_stat | grep free | awk '{ print $3 }' | sed 's/\.//')
INACTIVE_BLOCKS=$(vm_stat | grep inactive | awk '{ print $3 }' | sed 's/\.//')
SPECULATIVE_BLOCKS=$(vm_stat | grep speculative | awk '{ print $3 }' | sed 's/\.//')

FREE=$((($FREE_BLOCKS+SPECULATIVE_BLOCKS)*4096/1048576))
INACTIVE=$(($INACTIVE_BLOCKS*4096/1048576))
TOTAL=$((($FREE+$INACTIVE)))
echo Free:       $FREE MB
echo Inactive:   $INACTIVE MB
echo Total free: $TOTAL MB
share|improve this answer

Judging by your other question, I think you've found the use of the Activity Monitor utility to look at your memory status, right? Just for the record, it's in /Applications/Utilities/Activity Monitor.app.

share|improve this answer

You might try the command allmemory if you want a command line tool that reports on memory usage.

share|improve this answer
    
A powerful tool, but it's processor-intensive (around 95% of one of two CPUs on my MacBookPro5,2) and if much memory is used: a simple run of allmemory may be unexpectedly long — for me today, over four minutes per run, YMMV. A run of allmemory for sysdiagnose may take considerably longer. –  Graham Perrin Apr 30 '12 at 8:35
free="$(( $(vm_stat | awk '/free/ {gsub(/\./, "", $3); print $3}') * 4096 / 1048576)) MiB free"
share|improve this answer
1  
The current edition of that command does not work for me in tcsh (my default) or sh. Is the command shell-specific? –  Graham Perrin Apr 30 '12 at 8:21
    
Yes, it is bash and ksh specific. In tcsh try: set freeblocks=`vm_stat | grep free | awk '{ print $3 }' | sed 's/\.//'` ; set freeMB=`expr $freeblocks \* 4096 / 1048576`; set free=`echo $freeMB MiB free`. You can then do echo $free to print the amount of free memory. You could also create an alias: alias free echo $freeMB MiB free. –  jaume Feb 4 '13 at 8:58

Here's a simple one-liner to make the whole vm_stat output more human friendly:

$ vm_stat | perl -ne '/page size of (\d+)/ and $size=$1; /Pages\s+([^:]+)[^\d]+(\d+)/ and printf("%-16s % 16.2f Mi\n", "$1:", $2 * $size / 1048576);'
free:                     2330.23 Mi
active:                   2948.07 Mi
inactive:                 1462.97 Mi
speculative:               599.45 Mi
wired down:                840.46 Mi
copy-on-write:           43684.84 Mi
zero filled:            385865.48 Mi
reactivated:               608.14 Mi
share|improve this answer

The above is way too much effort for my liking, and it assumes that you have a fully fledged install too... If you've booted from a Mac OS X start up disk, then all the above solutions obviously won't work... Just use the command "hostinfo", here's the output from my mid 2012 MBAir running Mavericks (10.9.1):

 Mach kernel version:
 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE_X86_64
Kernel configured for up to 4 processors.
2 processors are physically available.
4 processors are logically available.
Processor type: i486 (Intel 80486)
Processors active: 0 1 2 3
Primary memory available: 8.00 gigabytes
Default processor set: 195 tasks, 961 threads, 4 processors
Load average: 1.61, Mach factor: 2.38

The good this about this command is that it comes preinstalled with the 10.9 installer too under /usr/bin, so it's very handy,

ideally, if you just want RAM then issue:

$ hostinfo | grep memory

Don't know if hostinfo exists on any previous OSes though...

share|improve this answer
    
How does hostinfo show used memory? –  patrix Jan 28 at 6:52

There's no exact equivalent that's distributed with Mac OS X, but there are a couple other ways to get the information:

  1. system_profiler - Shows all of the Mac's System Profile info in the shell
  2. sysctl -a | grep mem or sysctl hw.memsize (total mem)
share|improve this answer

Bash commands "free like" for Mac OSX.

This is the second reissue of this post. At first, I got two "-1". One because I was not describing in English, it is corrected. The other because I used "gawk" (which is not part of a standard OS X installation), it is also corrected, I now use "awk". The "-2" are still there ;-). The best is perhaps now to test and evaluate the commands it themselves?

I reviewed my first idea to build only one end-user oriented command with a friendly and highly configurable display, I made two:

  • free-like.sh a script always oriented "end user", with more accuracy, a "friendly" and configurable display, but with more calculations and resource consumption,

  • free-like-raw.sh, a command now oriented developer, sysadmin, etc.., with less computation and resource consumption, but also with less precision, less "friendly" display.

The data for the physical memory are extracted from the results of the command vm_stat (which returns the results in blocksize). The imprecision resulting from the transformation in bytes (number_of_blocks * block_size, the default value of the calculations) will be between 0 < the size of the block. The data for virtual memory are taken from the "top" command. The imprecision here is linked to the unit of reference of the "top" command: kilo, mega, giga.

Calculations are made using "awk" that respects rounded (as opposed to "bc"). "awk" is also quicker than "bc". You can see the test script here: http://myblog.robert.sebille.name/article29.html#awk-bc

You can view the results of the commands in bytes (default), in kilo, mega or giga, with x decimal places in the case of free-like.sh and if you ask the display in mega ou giga.

The scripts are too long for a post, but you can find them on this article of my blog: http://myblog.robert.sebille.name/article29.html

The article is in french, but it display one example of display for each command and their integrated help (./free-like.sh -h and ./free-like-raw.sh -h), in english. These aids completely describe the commands. The article display also the codes.

English is not my mother language. If somebody wants to correct errors in the integrated help, he is welcome ;).

yours.

share|improve this answer
    
Please descrive the article. Answers should stand alone without a link and in this case we need the explanation in English –  Mark May 11 '13 at 23:58
    
Besides being more or less unusable by somebody without any knowledge of French, your script seems to require gawk which is not part of a standard OS X installation. –  patrix May 12 '13 at 8:54
    
@patrix : Thank you for your feedback I will make a description in English and I will translate the integrated help too (currently in French). gawk: actually, I forgot, thank you. I met some localization issues (decimal comma or decimal point) with awk. They disappeared without knowing why. I came back to awk instead of gawk. I've needed a bit of time to adjust things, I will repost when it's ready. Yours. –  Robert May 12 '13 at 12:29
    
Simply replacing gawk with awk worked for me without issues. –  patrix May 12 '13 at 13:09

In case you're only really interested in swap usage (what would be the last line of output from free):

$ sysctl vm.swapusage
vm.swapusage: total = 64.00M  used = 0.00M  free = 64.00M  (encrypted)
share|improve this answer

The script at top is not very useful since top will display all those for you. Just use gui as mentioned or install linux and you will never go back. :)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.