前言
Java 中最通用的日志模塊莫過于 Log4j 了,在 python 中,也自帶了 logging 模塊,該模塊的用法其實和 Log4j 類似。日志是記錄操作的一種好方式。但是日志,基本都是基于文件的,也就是要寫到磁盤上的。這時候,磁盤將會成為一個性能瓶頸。對于普通的服務器硬盤(機械磁盤,非固態硬盤),Python日志的性能瓶頸是多少呢?今天我們就來測一下。下面話不多說,來一起看看詳細的介紹:
測試代碼如下:
#! /usr/bin/env python #coding=utf-8  # ============================ # Describe : 給平臺提供的日志 # D&P Author By:  常成功 # Create Date:  2016/08/01 # Modify Date:  2016/08/01 # ============================  import time import os import logging   print "Start test ...." s_tm = time.time() test_time = 10.0 # 測試時間10秒 e_tm = s_tm + 10 j = 0  pid = str(os.getpid()) while 1:  now_time = time.time()  j += 1  if now_time > e_tm:   break  # 生成文件夾  lujing = "d://test_log"  if not os.path.exists(lujing):   os.mkdir(lujing)   fm2 = '%Y%m%d'  YMD = time.strftime(fm2, time.localtime(now_time))   filename = 'recharge_' + YMD + '.log'  log_file = os.path.join(lujing, filename)  t = "/t"  log_msg = str(j) +t+ str(now_time) +t+ pid   the_logger = logging.getLogger('recharge_log')  f_handler = logging.FileHandler(log_file)  the_logger.addHandler(f_handler)  the_logger.setLevel(logging.INFO)  # To pass exception information, use the keyword argument exc_info with a true value  the_logger.info(log_msg, exc_info=False)  the_logger.removeHandler(f_handler)  rps = j/test_time print rps, "rows per second" 結果為:
Start test ....
2973.0 rows per second

Python的logging性能:
7200轉的機械磁盤,測了幾次,每秒的能寫入日志的行數(每行就是一條日志),數量基本在 2800-3000 之間。此時,磁盤IO基本已經跑滿。(在3.3Ghz的CPU上,CPU占用大約40%)。

Python的logging多進程:
python 的 logging模塊,是線程安全的。但對于多進程的程序來說,怎么去寫日志文件呢?我的解決辦法是,每個進程的PID,寫一個單獨的日志文件。再用算法把所有進程的日志合并起來,生成新的日志。
提示:由于磁盤IO已經到達瓶頸,所以多進程并不能提高日志性能。高性能日志,需要用緩存,或者分布式日志。
總結
以上就是這篇文章的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對武林站長站的支持。
新聞熱點
疑難解答