What is the best way to determine if the computer running my script is using swap memory? It should be as cross-platform as possible. One solution would be to run a program like top
as a subprocess, but I would hope there's a better way.

- 3,610
- 2
- 31
- 56
-
The command `free -m` might be of interest to you, as seen in [this article on nixCraft](http://www.cyberciti.biz/faq/linux-add-a-swap-file-howto/), section *How do I verify swap is activated or not?* – grooveplex Jun 11 '16 at 07:20
-
The most crossplatform method is occupy and fill memory untill you got exception, and at the end catch exception and print `I use swap memory` – fghj Jun 11 '16 at 08:41
-
2You can use `psutil`. It is not in the standard library but it is cross platform. You can get info on swap memory using `psutil.swap_memory()`. – Jun 11 '16 at 08:50
2 Answers
You can use the module psutil
. It is not a module in standard library though and you have to install it using pip
package manager.
pip install psutil
The swap usage data can be gathered using psutil.swap_memory()
. It returns a named tuple.
>>> import psutil
>>> psutil.swap_memory()
sswap(total=2097147904L, used=886620160L, free=1210527744L, percent=42.3, sin=1050411008, sout=1906720768)
I saw in this thread Stackoverflow: Profile Memory Allocation in Python an explanation of how you can record the use of your memory in real time. Then directly printed into a nice graph using mrpof
. (The thread is a bit old but still accurate I guess).
Here is the official documentation of the module: memory profiler pypi documentation
If you don't want to read the documentation, you first have to install the package via:
$ easy_install -U memory_profiler # pip install -U memory_profiler
And then use it on a script like this:
$ mprof run you_script_python.py
$ mprof plot
Which produce a file like this: (source)
Or more simply like this:
$ python -m memory_profiler you_script_python.py
Will produce the following output:
Line # Mem usage Increment Line Contents
==============================================
3 @profile
4 5.97 MB 0.00 MB def my_func():
5 13.61 MB 7.64 MB a = [1] * (10 ** 6)
6 166.20 MB 152.59 MB b = [2] * (2 * 10 ** 7)
7 13.61 MB -152.59 MB del b
8 13.61 MB 0.00 MB return a
It also works on windows. According to the author, Fabian Pedregosa, the module memory profiler
is cross-platform: Stackoverflow: Which Python memory profiler is recommended?
Sorry for all the links!