在 Linux 系统中,查看总剩余内存常用方法。
方法 1:使用 free
命令
free
是一个常用的命令,用于显示系统的总内存、已用内存、空闲内存和交换内存。
bash
free -h
-
-h
参数表示以易读的格式(如 GB、MB)显示内存信息。 -
输出示例:
total used free shared buff/cache available Mem: 15G 5.3G 2.1G 248M 8.2G 9.5G Swap: 2.0G 0B 2.0G
total
:总物理内存。used
:已使用的内存。free
:完全空闲的内存。available
:实际可用的内存(free + buff/cache
中可用于程序的内存)。
方法 2:使用 vmstat
命令
vmstat
是一个更通用的系统性能监控工具,也可以用来查看内存信息。
bash
vmstat -s
-
输出示例:
16384000 total memory 5570560 used memory 2129920 free memory 8388608 buffers
total memory
:总内存。free memory
:完全空闲的内存。buffers
和cached
:被系统缓存的内存,这些内存可以被程序使用。
方法 3:查看 /proc/meminfo
文件
/proc/meminfo
是一个虚拟文件,包含了系统的内存信息。你可以通过 cat
命令查看其内容。
bash
cat /proc/meminfo
-
输出示例:
MemTotal: 16384000 kB MemFree: 2129920 kB MemAvailable: 9748480 kB Buffers: 8388608 kB Cached: 8388608 kB
MemTotal
:总物理内存(以 KB 为单位)。MemFree
:完全空闲的内存。MemAvailable
:实际可用的内存。
方法 4:使用 top
或 htop
命令
top
和 htop
是常用的系统监控工具,它们可以动态显示系统的内存使用情况。
- 运行
top
或htop
,然后查看内存相关的列(如Mem
和Swap
)。
方法 5:使用 psutil
(Python 脚本)
如果你熟悉 Python,可以使用 psutil
库编写脚本来查看内存信息。
python
import psutil
mem = psutil.virtual_memory()
print(f"Total Memory: {mem.total / (1024 ** 3):.2f} GB")
print(f"Free Memory: {mem.free / (1024 ** 3):.2f} GB")
print(f"Available Memory: {mem.available / (1024 ** 3):.2f} GB")
总结
- 如果你只需要快速查看内存信息,推荐使用
free -h
。 - 如果你需要更详细的内存信息,可以查看
/proc/meminfo
文件或使用vmstat
。 - 如果你需要实时监控,可以使用
top
或htop
。