Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

Automatically reclaim memory from leaky programs UNIX
Sometimes applications have a nasty habit of claiming a lot of memory and never releasing it back to the system. Over time, this can cause affect performance. Most of the time, this can simply be fixed by quitting and restarting the offending program, but I wanted to find a more elegant solution.

After searching the Internet, I found few scripts that I could tweak to achieve what I wanted. Heres what I came up with. The first script is a python script I found at StackExchange by user drfrogsplat that gets information about system memory. The second is a bash script I wrote that runs the purge command if you have over a certain amount of inactive memory, in my case 500MB (probably overkill). Note that I think you need developer tools installed to use the purge command. There's probably an easier way to do this with vm_stat directly but I'm not good enough at awk/grep/sed to it figure out.

The bash script can be attached to a launchd plist to run automatically at certain intervals or whenever you want. I seems to work pretty well for me.
#!/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 )

==============================================================
==============================================================

#!/bin/bash

MM=`/Path/to/python/script.py | awk '/Inactive/ {print $3}'`

echo "Testing status of inactive free memory..."

if [ "$MM" -gt "500" ]; then
    echo "You have too much inactive free memory." $MM"MB Releasing now..."
    purge
    exit 0
else
    echo "Memory ammount" $MM"MB does not meet purge threshold."
    exit 0
fi
[kirkmc adds: I'm guessing that this will be controversial. There seem to be dozens of apps on the Mac App Store that free up memory, and I'm not convinced that this is necessary. The only time I would see this as being essential is if that inactive memory is leading to more paging. Lately, I've been amazed at how little paging my Mac mini does; with 8 GB RAM, it rarely uses more than one swap file, and this with an uptime of several days.

I think that, in most cases, if you encounter an issue with memory, it's just as simple to use the purge command in Terminal. And, yes, I do see certain applications and processes taking up a lot of memory, notably iTunes and WebProcess. But note that the purge command doesn't free up all inactive memory anyway.

And, can someone confirm that Xcode is needed to have the purge command? Mine is in /usr/bin, and I don't think Xcode installs anything there, at least any more, now that it gets put in /Applications.]
    •    
  • Currently 1.80 / 5
  You rated: 2 / 5 (10 votes cast)
 
[26,223 views]  

Automatically reclaim memory from leaky programs | 36 comments | Create New Account
Click here to return to the 'Automatically reclaim memory from leaky programs' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
About the purge command
Authored by: azeotropo on Apr 11, '12 08:09:50AM

About the purge command, I have two partitions with Snow Leopard and Lion respectively. On the Snow Leopard I have XCode installed so I can't tell, but I didn't install XCode on the Lion partition and there is a purge binary in /usr/bin.

I don't believe that installing XCode 4.0.2 on the Snow Leopard partition installed anything on the Lion partition, so it's almost sure that, at least under Lion, purge command is available without installing XCode.



[ Reply to This | # ]
About the purge command
Authored by: felibb on Apr 11, '12 11:12:17AM

Having a Lion partition only, and no Xcode, I have purge command available as well.



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: HairyPotter on Apr 11, '12 08:28:52AM
just open the terminal and type

purge

does the same effect.
---
- - - - - - - - - - - - - - - - - - - - - - -
My iPhone Apps
http://itunes.com/MagnoUrbano
- - - - - - - - - - - - - - - - - - - - - - -

please buy one :-


[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: arcticmac on Apr 11, '12 08:41:38AM

I recently ran across linuxatemyram.com, which does a nice job explaining the way this works on linux, which should be at least reasonably similar to Mac OS.

A key observation is that if your computer isn't paging memory to disk, you should only hurt performance by purging your disk cache. If, on the other hand, your system IS paging to disk a lot, a purge might help, but it also might not, since nominally the OS probably should have done it automatically for you to avoid paging in the first place. (not that it always works)

Also, I believe 'purge' is NOT part of the dev tools, although it's hard for me to confirm 100% since I do have them installed. xcode does install a number of tools in /usr/bin if you ask it to install the command line tools package (available in the xcode prefs), but on my system, all the items installed by that command have the same modification date, which is different from the date on 'purge', so I think it's installed with the OS.



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: Weaselboy on Apr 11, '12 08:49:50AM

I have Lion 10.7.3 and have not installed Xcode, and I see purge in /usr/bin



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: LordGilman on Apr 11, '12 09:02:39AM

The purge command (see http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man8/purge.8.html ) has nothing to do with leaky software. I strongly urge you to take down this hint as it does not do what it promises to do in the title and in most situations will only make things slower at a later time.



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: alexiskai on Apr 11, '12 09:03:38AM

Yes, purge has been part of Xcode. Workstations without Xcode installed typically do not have the purge command. This is because purge is designed to allow developers to test their apps in a "clean" environment, i.e. one in which the OS has nothing in cached memory, without needing to reboot.

I concur with the above comment: in my experience, the benefits of running purge as a "memory cleaner" are illusory. The only possible benefit might be in a situation where a memory bottleneck is causing the system to become severely degraded. Even then I'm not sure it does much. In most cases, users experiencing such bottlenecks would find it a better use of their time and money to just go buy more RAM.



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: sosullivan on Apr 11, '12 09:17:12AM

Just for the record, Purge works fine without Xcode on one's system. Just tested it, and WOW! :)

---
I miss my apostrophe....



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: gmachen on Apr 11, '12 09:26:54AM

Please do NOT take down this hint!

When I bought more RAM expressly to address Inactive Memory paging, all it did was just put off the inevitable until later. No matter how much RAM one installs, when Inactive fills-up, the thrashing starts. This is just stupid to me; Inactive is supposed to reduce disk access, why turn around and let it page at all?!



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: astrosmash on Apr 11, '12 11:55:42AM

Your computer will always try to utilize as much RAM as possible to make your computer run faster, and this shows up a "inactive" RAM. High inactive RAM is what you want.

You bought more RAM to make your computer run faster. Your computer runs faster when it caches data in RAM instead of on disk.

This script undoes all of that caching. This script makes your computer run slower. It is the exact opposite of what you want.



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: gmachen on Apr 11, '12 12:15:55PM

^ Utterly fails to address one single issue I raised.
Yes, my "computer runs faster when it caches data in RAM instead of on disk," but I'm talking about when that Inactive Memory "cache" starts paging to disk. Seems to me that there's no excuse for Inactive Memory ever hitting the hard disk virtual memory scratch files; it should just be "forgotten" at that point. "High inactive RAM" may be what I want, but it is precisely when Inactive Memory becomes high that the disk thrashing & sluggishness begins. If running the script (or Purge, which is what I do when it happens) "makes your computer run slower," then why does doing so restore my robust performance to that of a freshly booted computer? Indeed, before I discovered Purge, I had to wait for a reboot to clear things up, when that wait became preferable to a miserable ongoing fit of usability-sucking spinning beachballs and accumulating scratch files.... And to repeat, no matter how much RAM one adds, it only delays the performance hit until Inactive Memory eventually fills up. (If you watch Inactive Memory, it often rises & falls with use, but sooner or later something you're doing will not occasion its reclamation, and when it "red-lines," that's when the usability degradation commences.)

Edited on Apr 11, '12 12:21:52PM by gmachen



[ Reply to This | # ]
Previously refuted
Authored by: lullabud on Apr 11, '12 09:44:35AM
This hint has already been posted in another more basic form and was refuted at that time too.
$ man purge | cat

purge(8)                  BSD System Manager's Manual                 purge(8)

NAME
     purge -- force disk cache to be purged (flushed and emptied)

SYNOPSIS
     purge

DESCRIPTION
     Purge can be used to approximate initial boot conditions with a cold disk
     buffer cache for performance analysis. It does not affect anonymous mem-
     ory that has been allocated through malloc, vm_allocate, etc.

SEE ALSO
     sync(8), malloc(3)

                              September 20, 2005


[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: vykor on Apr 11, '12 10:17:03AM

purge does not affect memory allocated via malloc (it says so right in the man page). malloc() is the primary system call used to allocate main memory to individual processes. Memory leaks, in the classic definition, is usually applied to this exact scenario: memory allocated via malloc(), but not free()'ed. The title of this piece is largely inaccurate -- purge does not reclaim memory lost via program memory leaks.

It does blow away the disk cache buffer, which for some reason does grow inordinately large on OS X. In most cases, however, this is not the appropriate solution, if the source of your memory problems is a memory leak in one of your long-running apps (I'm looking at you, Safari). It will also likely degrade system performance perceptibly until the buffer caches are rebuilt.

Edited on Apr 11, '12 10:19:53AM by vykor



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: wallybear on Apr 11, '12 11:05:39AM

You can completely replace the python script just substituting this line in your bash script:

MM=`/Path/to/python/script.py | awk '/Inactive/ {print $3}'`

with this one:

MM=`vm_stat | awk '/inactive/ {print int($3*4/1024)}'`



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: wallybear on Apr 11, '12 06:06:27PM

And this is a bash one-liner that mimics the python script, using awk only:

vm_stat | awk '/Pages.(active|inactive|wired.down|free)/ { sub("Pages ","",$0) ; for (i=1;i<=NF;i++){sub(".",substr(toupper($i),1,1),$i)}; sub(":"," Memory:",$0) ; printf("%-20s %5.2d Mb\n", substr($0,1,index($0,":")), $NF*4/1024) }' ; sysctl -a | awk '/hw.memsize:/ {printf("%-20s %5.2d Mb\n", "Real Memory:", $2/1024/1024)}'

(not elegant, I agree, but it does the job)



[ Reply to This | # ]
RAM
Authored by: leamanc on Apr 11, '12 12:04:34PM

While I find hints like this useful from a tech perspective, I believe what Kirk says is most appropriate to this discussion. RAM is very cheap these days, and if you can afford a new(ish) Mac, you can probably afford to max out the RAM too--not from Apple but a reputable third-party, of course! Only the 1% can afford to max out RAM from Apple!

But, back on track here...you will never have need for this or the 'purge' command, or any of those memory-clearing apps from the App Store if you load up on RAM. And your system will run considerably faster on a day-to-day basis too. We live in a great time when RAM is really cheap, hard drives are incredibly spacious, processing power in sub-$1,000 systems beats workstations from 10 years ago, and solid-state drives are moderately affordable. Sink a little extra into your system and I can't see anyone needing to do little performance tweaks like this.



[ Reply to This | # ]
RAM
Authored by: kirkmc on Apr 11, '12 01:17:03PM

What you say about the price of RAM is only partially true. I have 8 GB in my Mac mini; the maximum that I can have without going to expensive RAM sticks. And my MacBook Air is not upgradeable, and is limited to 4 GB.

I don't really have problems with RAM, given the type of work I do, except when I run Fusion, which ideally requires more than the 8 GB in my Mac mini.

---
Mac OS X Hints editor - Macworld senior contributor
http://www.mcelhearn.com



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: StanS on Apr 11, '12 12:50:59PM

Owners of Mabook Airs cant upgrade their physical System-Ram. 4 GB is the Limit.

So the opportunity to free up your Ram (without a restart of the system) is very useful.

'Purge' works on OSX Lion without Developer Tools (xcode). Just open your Terminal, type 'purge' - and done... Very useful if you had opened memory-eating apps. But some apps never release the ram back to the system. And also some kernel-processes do not release ram.

It would be great if the development of the script would continue. Until now I can not avoid, that I have to reboot the system periodically. There should be more elegant solutions.



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: nschum on Apr 11, '12 01:00:59PM

There is no way to reclaim "leaked" memory other than quitting the app.

"Leaked" memory is memory the application forgot it had and never frees. There is no way of telling from the outside which memory is a leak and which is needed. The hint is wrong about that.

"Inactive" memory is memory the app has released, but the OS is keeping around "just in case" but can throw out if needed. If you want to believe purging this memory helps, fine. But it has nothing to do with bad applications. If anything there's a bug in the OS when inactive memory isn't used.



[ Reply to This | # ]
Version 2.0
Authored by: desepticon on Apr 11, '12 04:12:08PM

Here's Version 2. It only requires one script. I've been reading some of the comments and perhaps what this is doing isn't reclaiming leaked memory, but I do feel system performance for an individual program is improved when you need high performance or have older hardware. 500MB was probably a little too high so I made it around 1 GB. Change to your liking.

#!/bin/bash

# This script checks the available inactive memory.
# Memory is purged if the available number of MB is
# greater than the following "msize" variable. Attach
# this script to launchd to run it periodically.

msize=1200

VS=`vm_stat | awk '/Pages\ inactive\:/ {print $3}' | sed 's/\.//g'`
MM=`echo "$VS/255" | bc`

echo "Testing status of inactive free memory..."

if [ "$MM" -gt "$msize" ]; then
echo "You have too much inactive free memory." $MM"MB Releasing now..."
purge
exit 0
else
echo "Memory amount" $MM"MB does not meet purge threshold."
exit 0
fi



[ Reply to This | # ]
New Memory Wipe Command
Authored by: desepticon on Apr 11, '12 06:12:37PM

Okay I've done I bit of searching and I've come up with this: http://forums.macrumors.com/showthread.php?t=142719&page=3

About 1/3rd of the way down, user "theshadow27" has posted a link to a C++ program with an XCodeProject file and a ruby script that appears to call malloc to clear the inactive memory. I've compiled the program successfully in Xcode and it seems to work as described. I've only done some preliminary tests but this program/script combo could be used instead of the purge command to accomplish the task more effectivley.

He also had this to say about the whole "Inactive Memory" Issue:

"From my informal tests, the system is more responsive when running with "Free Memory" than "Inactive Memory." As a computer scientist and electrical engineer to me the reason for this is fairly straight forward. When the Kernel has free memory to work with, it can allocate it without thinking. When it's inactive memory, no matter how fast/efficient/wonderful the MMS is, it still has to page out that data. What "clearing the inactive ram" means to me is:
--Forcing the Apple MMS to preemptively page inactive memory to disk so it is not done at the time of allocation.--"

Can anyone take a look a this program and tell me a little more about what it's doing and if its a step in a better direction. Is there any way this can be altered to better suit our purpose?



[ Reply to This | # ]
New Memory Wipe Command
Authored by: arcticmac on Apr 11, '12 09:06:59PM

It's certainly true that it adds complication to the system to have to clear inactive memory before it can allocate more, but it doesn't account for much time, and it turns out that what was in that memory was often useful.

The way his program works (which is essentially the same as the one I linked to in my comment above) is to allocate all of your free ram, thus (assuming things are working properly) forcing the kernel to flush the disk cache, which is essentially the same operation that purge performs, though it wouldn't surprise me if 'purge' does it in a more efficient way.

As a little experiment, open a terminal and run 'time purge'. Then run it again. Notice that it doesn't take dramatically less time to run the second time than the first. Now try switching back to your web browser. Notice how it takes a bit longer than usual the first time for the window to become "active" again? Try launching a new app (e.g. I did 'open -a "Activity Monitor"' in the terminal). Notice how long it takes. Quit it and launch it again. Unless it's a much bigger app than Activity Monitor, it appears almost instantly. I think it's pretty clear that the disk cache does serve some definite value, and that clearing it too often is probably not a good idea.

On the other hand, I'll also grant that the system doesn't work perfectly. There are certainly times when I'm sitting there on top of 3/4 of a GB or more of cache/inactive memory and my system gets busy swapping away some memory or other to disk to make room for the latest thing. Which is _not_ good for performance either. Sometimes it might be worthwhile to 'purge' in a situation like that, but really it depends. Often as not, I find that quitting Safari or Xcode or Matlab or any of my other big memory-hogs is a bigger help.

What I'm trying to say is that there might be situations in which 'purge' can help, but that you shouldn't just assume that it actually makes things faster just because the 'free' RAM went up; and I definitely wouldn't advocate running it automatically repeatedly unless you have solid evidence that it increases system performance for the particular task at hand.



[ Reply to This | # ]
New Memory Wipe Command
Authored by: desepticon on Apr 11, '12 10:34:24PM

Thanks for the info. It seems to me that this guys program does something a little different from purge though. It causes no noticeable lag on my system when run. When I run purge it takes a few seconds and the system hangs. I'm not sure this program is affecting the disk cache at all. It doesn't seem to be as vicious about reclaiming memory.

Like you say I think this practice can be used in certain situations. In my case I run a Plex media server. This program has the habit of claiming more and more RAM over time and being stingy about releasing it back to the system. The computer I run this server on also multi-purposes as a MediaMac, Game System, WebServer,rtorrent setup, and generic purpose computing hub. In some instances, especially when I want to play a game, it seems to be best to start with as fresh a canvas as possible as far as inactive memory is concerned. I don't know when I might feel like playing a game, so a script such as this running automatically would allow me to "set it and forget it."

Hmmm. Thinking about this now wouldn't it be possible to attach a lauchctl watchpaths directive for certain applications you want maximum memory performance from? Does watchpaths support multiple paths?



[ Reply to This | # ]
Version 2.0
Authored by: wallybear on Apr 12, '12 03:06:25AM

VS=`vm_stat | awk '/Pages\ inactive\:/ {print $3}' | sed 's/\.//g'`
MM=`echo "$VS/255" | bc`

Why not use this:

MM=`vm_stat | awk '/Pages\ inactive\:/ {print int($3/256)}'´

Same result, less calls.



[ Reply to This | # ]
Version 2.0.1
Authored by: wallybear on Apr 12, '12 03:39:07AM
More concise script:

#!/bin/bash

# This script checks the available inactive memory.
# Memory is purged if the available number of MB is
# greater than the following "msize" variable. Attach
# this script to launchd to run it periodically.

msize=1200

MM=`vm_stat | awk '/Pages\ inactive\:/ {print int($3/256)}'`

echo "Testing status of inactive free memory..."

if [ "$MM" -gt "$msize" ]; then
  echo "You have too much inactive free memory. ${MM}MB Releasing now..."
  purge
else
  echo "Memory amount ${MM}MB does not meet purge threshold."
fi
("exit 0" is redundant, it's the standard exit code of a shell script in case of no errors.)
Edited on Apr 12, '12 03:49:00AM by wallybear


[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: TGV on Apr 12, '12 12:04:47AM

The statement that you cannot reclaim memory from a leaky application using purge is completely right. The only thing purge will do is to clear the disk buffers. These buffers contain the files you recently accessed (it's a little bit more complicated, but well), so that if you need to access them again, they can be retrieved from memory. OSX uses free memory for those buffers, and releases disk buffer space as soon as more memory is needed.

HOWEVER ... I have an application, actually a plugin in Logic, that checks for the amount of free memory and changes its behavior when that drops below 1GB. It also scans lots of files on starting up. To make it run smoothly, I do clear out memory if free memory goes towards 1GB.



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: lsequeir on Apr 12, '12 02:29:17AM

In Snow Leopard, "purge" is not installed by default, but will come as part of the developer tools. In Lion, it is there by default. That's why some people say they have it and others don't.

Although clearly the title of the hint is wrong - as others have pointed out, "purge" does not reclaim memory from "leaky" applications - nevertheless the problem of Inactive Memory filling up RAM to the point where paging slows your Mac to a crawl is VERY REAL and purge does help in that situation. This is not a bug in any application, is a problem with the OS itself - and it seems to be more severe with Lion. I have seen dozens if not hundreds of complaints in Apple discussions about Final Cut beach-balling that in truth are due to this very issue.

Yes, more RAM always helps, but the problem is real and lies with how the OS handles memory.

---
LuĂ­s



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: timrichardson on Apr 12, '12 04:29:49AM

man purge tells you that it clears the disk cache to approximate conditions of a cold boot. Ie, before you hit the disk for anything. If you really like purge, you can make its benefits permanent.
1) Open your mac
2) remove one of the memory modules
This works because disk cache is an OS luxury: using spare RAM to improve performance. Get rid of the spare RAM, and you'll reduce the size of disk cache.

Disk is slow. RAM is fast. That's what a disk cache is. It uses some RAM to avoid going back to the slow disk.
Apple has a long track record of OS X kernels for desktop and server use, and BSD is a very mature platform. If you purge the disk cache, the OS will just fill it again because it's the smart thing to do.
The disk cache has nothing to do with leaking memory.
Leaking memory is a problem which can not be fixed except by terminating the offending process (or fixing the bug in the software). Leaking memory is when a program allocates space to an object, and doesn't reclaim it when the object is destroyed. Then it creates the object again, grabbing more memory. If this process repeats, memory leak. The OS has no idea this is happening, and there is no terminal command that can fix it.

I get days of uptime on my mac using a variety of typical software, and I don't believe memory leaks are a problem.



[ Reply to This | # ]
Delete incorrect hint
Authored by: SeanAhern on Apr 12, '12 08:44:40AM

This hint isn't just controversial; it's flat out wrong. As others above have pointed out, it's not possible to reclaim memory from leaky applications in any way other than quitting them. And purge-ing is of questionable utility anyway.

I would recommend that kirkmc delete the hint entirely so that it doesn't mislead people with incorrect information.



[ Reply to This | # ]
Delete incorrect hint
Authored by: desepticon on Apr 12, '12 10:17:42AM

While I see that it may be mis-titled, it seems from some of the comments, and my own experience, that there is some benefit to the purge command in certain situations. I also linked to an alternative to purge that may do a different type of memory reclamation. If the post were reedited to reflect the contents of subsequent comments I think this would make an informative and useful hint.



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: Superboy on Apr 12, '12 11:19:07AM

As others have stated, this hint is completely incorrect. It doesn't reclaim memory from leaky programs.

As the OS runs and the user opens apps, spare (or free) memory is filled up with data that's read directly from the disk, making subsequent accesses to the same data much faster. The part of memory used for disk caching is known as "inactive" memory. Purging this inactive memory increases free RAM yes, but at the expense of forcing all the cached data to be re-read from disk when it's needed. This is bad not only because the HDD is hundreds of times slower than RAM, but also because much of the data that's being reloaded from disk has to be processed again. If an app really needs more memory than is available at a given time, the OS will intelligently purge stale "inactive" memory pages, increasing free memory as required.

There really is no need to purge RAM when inactive memory reaches XXXmb. "Purge" is a debugging tool, it's not supposed to be used willy nilly, it's especially useless in that it actually slows down the OS.

I'm pretty sure Apple is au fait with how their OS works, they'd build an auto-memory-purger into the kernel if it was necessary. Apple removed all the memory freeing apps from the App Store a few years ago, shouldn't that be a good enough sign that it's not a good thing to do?

Edited on Apr 12, '12 11:19:32AM by Superboy



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: metiure on Apr 12, '12 02:20:16PM

Or, you can just live longer and happier by completely disabling virtual memory:
http://hints.macworld.com/article.php?story=201106020948369



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: petersconsult on Apr 13, '12 06:40:54AM
Try this to get your memory stats:

top -l 1 | awk '/PhysMem/ {print "Wired: " $2 "; Active: " $4 "; Inactive: " $6 "; Used: " $8 "; Free: " $10}'

[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: iandol on Apr 17, '12 10:22:23AM

Please change the title of this post to not promulgate the incorrect use of purge to "fix" leaky programs!!! Enough commenters here have given you clear documentation about what purge and "freeing" inactive memory does; the title is flat wrong.

Does this really do anything useful on a working production system; I doubt it does. Some users subjectively claim it helps, though many of these are simply beguiled by seeing more FREE RAM and thus assume things are better (placebo). No one has clearly objectively benchmarked its benefit.

But hey, maybe a simple terminal command really does more good than the fruits of labour of hundreds of computer scientists working thousands of man hours engineering virtual memory systems that handle memory on modern computers...



[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: marianmi on Jun 09, '12 05:13:16PM
I have to add my comment to this thread, since most of the people here don't want to understand how useful the purge command is. While generally I can't complain most of the times about the memory management in OS X, in some versions of Snow Leopard it was was quite bad. Leopard and Lion were/are better.
In any case, the idea is that some machines are memory limited - the macbook airs (4GB), my old 2007 macbook pro (4GB). Even if you could add more RAM (I may go up to 6GB), it would not make sense (change of machine soon, losing dual channel,...).
While the disk cache is heaven on earth when having loads of RAM, it's not for the rest of us. Take Safari - just after a search on google, you open up dozens of pages to see if they have what you search. Most of them don't. You close them. You will not open them again. They are still in the cache, eating up your memory. You ran out of Free Memory. Safari SHOULD release the Inactive, but most of the time it does not. The end result: you have LOTS of swapping because of the Inactive Memory caching crap.
To the guy that said to remove one DIMM to make the change permanently: if you like caching so much, open up all of your apps in /Applications, and let them sit in the background. Run your computer like that PERMANENTLY without restarting. You might want to play Chess.app in a week of two, and when you do, it will start so much faster /s Yeah, RAM is faster than DISK, but swapping like hell is so much slower than loading once into Free Memory.
In conclusion, you have lots of RAM, don't look here. But don't bash this hint, which is SO useful for many people. You might want to change the name about leaking memory though. That's wrong.

[ Reply to This | # ]
Automatically reclaim memory from leaky programs
Authored by: Yoyo22 on Jan 14, '13 05:04:26AM

Using perl, this is rather easy... add the following to your cron setup ('crontab -e' using terminal):

5,15,25,35,45,55 * * * * top -l 1 | perl -ne 'if($_ =~ m/.*?(\d+)M inactive.*/){if($1 > 800 ) {$g="/usr/local/bin/growlnotify -mPurge:$1"; `$g`;`purge`}}'

the above activates every 10 minutes and if inactive memory is greater than 800MB it runs purge (plus growlnotify message in relation)... this seems to help on an older 2007 macbook pro with 6GB ram (and very much so in specific usage situations, that do not fit the tuned algorithm). It also includes an easy way to get growlnotify to work in conjunction with perl oneliners.



[ Reply to This | # ]