python垃圾回收,判断内存占用,手动回收内存,二
以下为例子,判断计算机内存并释放程序内存。
# coding=utf8
import time
import psutil, gc, commands,os from logger_until import LoggerUntil
from until import keep_circulating logger = LoggerUntil(name="Monitor").getlog(logfilename='Monitor.log', loglevel=2, add_StreamHandler=1) need_monitor_procces_names = [ ##需要检测的进程的cmd命令放到这里,支持模糊匹配
'touna0627.py',
'dailiip.py',
'redis-server',
'mongod',
] class Monitor(object):
def __init__(self):
self.specified_process_list = self.get_specified_process()
self.current_process = self.get_current_process() @staticmethod
def print_all_cmdlines():
for pid in psutil.pids():
p = psutil.Process(pid)
print p.cmdline() @staticmethod
def get_specified_process():
all_pids = psutil.pids()
process_list = []
for pid in all_pids:
p = psutil.Process(pid)
p_cmdline = p.cmdline()
for argx in p_cmdline:
for name in need_monitor_procces_names:
if argx.find(name) > -1:
if p.status() != 'stopped':
process_list.append(p) p_pid_set = set()
process_list2 = []
for p in process_list:
if p.pid not in p_pid_set:
process_list2.append(p)
p_pid_set.add(p.pid)
return process_list2 @staticmethod
def monitor_system():
psutil.cpu_percent()
time.sleep(1)
mem = psutil.virtual_memory() mem_total = mem.total / 1000000
mem_available = mem.available / 1000000
mem_percent_str = str(mem.percent) + '%' cpu_count = psutil.cpu_count()
cpu_percent_str = str(psutil.cpu_percent()) + '%' msg = '本机总内存是:{0}M , 本机可用内存是:{1}M, 本机内存使用率是:{2}, 本机cpu核数是:{3}, 本机cpu使用率是:{4}\n\n'.format(mem_total, mem_available, mem_percent_str, cpu_count, cpu_percent_str)
logger.info(msg) def monitor_specified_process(self):
for p in self.specified_process_list:
p.cpu_percent(None)
time.sleep(1)
for p in self.specified_process_list:
# p = psutil.Process(0)
""":type :psutil.Process"""
cmdline_str = ' '.join(p.cmdline()).ljust(60, ' ')
p_cpu_percent_str = str(round(p.cpu_percent(), 2)) + '%'
p_memory_percent_str = str(round(p.memory_percent(), 2)) + '%'
p_strated_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(p.create_time()))
p_pid_str = str(p.pid) msg = '进程' + cmdline_str + ' 的pid是:' + p_pid_str + ' cpu使用率是:' + p_cpu_percent_str + ' 内存使用率是:' + p_memory_percent_str \
+ ' 进程的启动时间是:' + p_strated_time
logger.info(msg) @staticmethod
def get_current_process():
return psutil.Process() def is_need_release(self,threshold):
print self.current_process.memory_percent()
if self.current_process.memory_percent() < threshold:
return 0
else:
logger.info('回收当前 %s 进程id的内存' % self.current_process.pid)
return 1 def free_current_process_memory(self, threshold):
"""回收python所处的当前进程的内存"""
if self.is_need_release(threshold) == 1:
gc.collect() class MemoryReleaser():
def __init__(self,threshold,cmd_name_str='touna0627.py'):
"""
:type threshold:float
"""
self.threshold = threshold # 内存使用率的阈值
self.cmd_name_str =cmd_name_str
self.stutus, self.output = self.__get_memory_available() def __get_memory_available(self):
# status, output = commands.getstatusoutput("free -m | grep Mem | awk '{print $4}'") ##shell命令查询计算机可用内存
status, output = commands.getstatusoutput("ps aux | grep %s | sort -k4,4nr|head -1| awk '{print $4}'"%(self.cmd_name_str)) ##shell命令查询程序的内存使用率
return status, output def release_memory(self):
if float(self.output) > self.threshold:
logger.info('程序的内存使用率是 {}% ,程序需要释放内存'.format(self.output))
gc.collect() @keep_circulating(10)
def monitoring():
MemoryReleaser(40).release_memory() ###这一行来释放内存
monitor = Monitor()
monitor.monitor_specified_process()
monitor.monitor_system() if __name__ == "__main__":
pass
a = list(range(10000000))
del a
time.sleep(30)
monitoring()
如果把MemoryReleaser(600).release_memory() 注释掉,程序将一直是占用大内存。
程序中使用了
free -m | grep Mem | awk '{print $7}'
来判断计算机可用内存。 虽然psutil可以判断内存,但使用psutil判断内存,内存就无法回收了。 把MemoryReleaser(600).release_memory() 放到monitoring函数中的最后一行,那就回收不了内存了。 尝试了很多次使用
gc.collect() 这种方式不能回收内存。
写成if true是可以回收内存的。
python垃圾回收,判断内存占用,手动回收内存,二的更多相关文章
- linux下使用free命令查看实际内存占用(可用内存)
转:http://blog.is36.com/linux_free_command_for_memory/ linux下在终端环境下可以使用free命令看到系统实际使用内存的情况,一般用free -m ...
- C&C++动态分配内存(手动分配内存)三种方式
1. malloc函数 函数原型:void *malloc(unsigned int size)函数的作用是:在内训的动态存储区开辟一个size个字节的连续空间,返回所分配区域的首字节地址. 可以看到 ...
- python 垃圾回收笔记
目录 引用计数 python内部的引用计数机制 循环引用 调试内存泄漏 总结 python 程序在运行的时候,需要在内存中开辟出一块空间,用于存放运行时产生的临时变量:计算完成后,再将结果输出到永久性 ...
- linux内存源码分析 - 内存回收(整体流程)
本文为原创,转载请注明:http://www.cnblogs.com/tolimit/ 概述 当linux系统内存压力就大时,就会对系统的每个压力大的zone进程内存回收,内存回收主要是针对匿名页和文 ...
- (转)linux内存源码分析 - 内存回收(整体流程)
http://www.cnblogs.com/tolimit/p/5435068.html------------linux内存源码分析 - 内存回收(整体流程) 概述 当linux系统内存压力就大时 ...
- Windbg分析高内存占用问题
1. 问题简介 最近产品发布大版本补丁更新,一商超客户升级后,反馈系统经常奔溃,导致超市的收银系统无法正常收银,现场排队付款的顾客更是抱怨声声.为了缓解现场的情况, 客户都是手动回收IIS应用程序池才 ...
- Egret在Chrome浏览器中的内存占用(内存泄露)
参考: 怎样查看Chrome的内存占用情况 JS内存泄漏排查方法(Chrome Profiles) chrome内存泄露(一).内存泄漏分析工具 chrome内存泄露(二).内存泄漏实例 目录: 一 ...
- Linux使用free命令查看实际内存占用
转自:http://www.cnblogs.com/pengdonglin137/p/3315124.html Linux下在终端环境下可以使用free命令看到系统实际使用内存的情况,一般用free ...
- Sciter/HTMLayout内存占用评测
先从最基础的Exe文件的执行说起: Exe文件要在系统中执行,首先要将Exe文件本身加载入内存中,并且通常在内存中加载完成的Exe所占空间大小会比实际所占的磁盘空间大一些,这是由内存的特殊设定所决定的 ...
随机推荐
- VMware下的Centos7联网并设置固定IP
安装CentOS7之后总得联网呀,而且不能一直连服务器,我们需要一个其他工具连它,所以一个固定IP也很重要了. 工具/原料 CentOS7 VMware 方法/步骤 首先设置vmware能 ...
- UEFI Protocol
MEM_INFO_PROTOCOL MEM_INFO_PROTOCOL; EFI_LOADED_IMAGE_PROTOCOL EFI_DEVICE_PATH_PROTOCOL EFI_DRIVER_B ...
- SpringBoot 开启 Actuator
在生产环境中,需要实时或定期监控服务的可用性.spring-boot 的actuator(监控)功能提供了很多监控所需的接口.简单的配置和使用如下: 1.引入依赖: <dependency> ...
- CentOS 7系统LAMP配置PHP-FPM的示例
CentOS 7 系统出来有一段时间了,今天我们来看在vps中的 CentOS 7 中给lamp环境配置php-fpm的过程,希望文章可以帮助到各位. CentOS 7 已经发布,并且采用 Apach ...
- click只能点击一次
<select id="s_province" name="s_province" class="s_province">< ...
- C/C++文件输入输出操作——FILE*、fstream、windowsAPI
基于C的文件操作在ANSI C中,对文件的操作分为两种方式,即流式文件操作和I/O文件操作,下面就分别介绍之. 一.流式文件操作这种方式的文件操作有一个重要的结构FILE,FILE在头文件stdio. ...
- hbase分页应用场景及分页思路与代码实现
转自:http://www.aboutyun.com/forum.php?mod=viewthread&tid=7030&extra=page=1 可以带着下面问题来阅读1.hbase ...
- 关于GO语言遇到illegal UTF-8 encoding 随手记录
在使用汉字的时候会报错 解决方案 editpad++ 修改编码为UTF-8 保存就可以了~bingo
- FPGA中的时序分析(三)
验证公式正确性 前两篇博客提及了关于时序的建立余量和保持余量的计算.结合实际情况,验证公式的运算正确性.结合之前博客提及的LED实验,看一下建立余量和保持余量是否都合格. 建立余量 图1是最大时钟 ...
- Playing FPS Games with Deep Reinforcement Learning
论文不同点: (1)用两套网络分别实现移动和射击. (2)使用LSTM来处理不完全信息. 疑问: (1)为什么对于射击使用RNN,对导航却没有使用RNN.一般来说,当我们看见视野里面有敌人的时候,我们 ...