是否有一种方法可以让Python程序确定它当前使用了多少内存?我看到过关于单个对象的内存使用情况的讨论,但我需要的是进程的总内存使用情况,这样我就可以确定何时需要开始丢弃缓存的数据。
当前回答
对于Python 3.6和psutil 5.4.5,使用这里列出的memory_percent()函数更容易。
import os
import psutil
process = psutil.Process(os.getpid())
print(process.memory_percent())
其他回答
对于Unix系统,如果您传递-v,命令time (/usr/bin/time)将提供该信息。参见下面的最大驻留集大小,这是程序执行期间使用的最大(峰值)真实(而不是虚拟)内存:
$ /usr/bin/time -v ls /
Command being timed: "ls /"
User time (seconds): 0.00
System time (seconds): 0.01
Percent of CPU this job got: 250%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 0
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 315
Voluntary context switches: 2
Involuntary context switches: 0
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
在unix上,你可以使用ps工具来监视它:
$ ps u -p 1347 | awk '{sum=sum+$6}; END {print sum/1024}'
其中1347是某个进程id。同样,结果的单位是MB。
import os, win32api, win32con, win32process
han = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION|win32con.PROCESS_VM_READ, 0, os.getpid())
process_memory = int(win32process.GetProcessMemoryInfo(han)['WorkingSetSize'])
对于Python 3.6和psutil 5.4.5,使用这里列出的memory_percent()函数更容易。
import os
import psutil
process = psutil.Process(os.getpid())
print(process.memory_percent())
下面是我的函数装饰器,它可以跟踪这个进程在函数调用之前消耗了多少内存,在函数调用之后使用了多少内存,以及函数执行了多长时间。
import time
import os
import psutil
def elapsed_since(start):
return time.strftime("%H:%M:%S", time.gmtime(time.time() - start))
def get_process_memory():
process = psutil.Process(os.getpid())
return process.memory_info().rss
def track(func):
def wrapper(*args, **kwargs):
mem_before = get_process_memory()
start = time.time()
result = func(*args, **kwargs)
elapsed_time = elapsed_since(start)
mem_after = get_process_memory()
print("{}: memory before: {:,}, after: {:,}, consumed: {:,}; exec time: {}".format(
func.__name__,
mem_before, mem_after, mem_after - mem_before,
elapsed_time))
return result
return wrapper
当你用它来装饰某个函数时
from utils import track
@track
def list_create(n):
print("inside list create")
return [1] * n
你将会看到这样的输出:
inside list create
list_create: memory before: 45,928,448, after: 46,211,072, consumed: 282,624; exec time: 00:00:00
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录