python記憶體回收,判斷記憶體佔用,手動回收記憶體,二

來源:互聯網
上載者:User

標籤:post   使用率   pid   ati   查詢   icm   names   collect   local   

以下為例子,判斷電腦記憶體並釋放程式記憶體。

# coding=utf8import timeimport psutil, gc, commandsfrom logger_until import LoggerUntilfrom until import keep_circulatinglogger = 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):        self.threshold = threshold        self.stutus, self.output = self.__get_memory_available()    @staticmethod    def __get_memory_available():        status, output = commands.getstatusoutput("free -m | grep Mem | awk  ‘{print $7}‘")  ##shell命令查詢電腦可用記憶體        return  status, output    def release_memory(self):        if float(self.output) < self.threshold:            logger.info(‘電腦可用記憶體是 %sM ,程式需要釋放記憶體‘%self.output)            gc.collect()@keep_circulating(10)def monitoring():    MemoryReleaser(600).release_memory()     ###這一行來釋放記憶體    monitor = Monitor()    monitor.monitor_specified_process()    monitor.monitor_system()if __name__ == "__main__":    pass    a = list(range(10000000))    del a    monitoring()

 

如果把MemoryReleaser(600).release_memory() 注釋掉,程式將一直是佔用大記憶體。

 

程式中使用了 

free -m | grep Mem | awk  ‘{print $7}‘
來判斷電腦可用記憶體。

雖然psutil可以判斷記憶體,但使用psutil判斷記憶體,記憶體就無法回收了。

把MemoryReleaser(600).release_memory() 放到monitoring函數中的最後一行,那就回收不了記憶體了。


嘗試了很多次使用
 if psutil.Process().memory_percent() > 0: 
  gc.collect()

這種方式不能回收記憶體。
寫成if true是可以回收記憶體的。



 

python記憶體回收,判斷記憶體佔用,手動回收記憶體,二

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.