2010-03-19 107 views
0

我正在開發一個記錄器守護進程來抓取mongodb數據庫上的日誌魷魚。但我正在經歷太多的CPU利用率。我如何優化這段代碼?如何優化此代碼?


from sys import stdin 

from pymongo import Connection 

connection = Connection() 
db = connection.squid 
logs = db.logs 
buffer = [] 
a = 'timestamp' 
b = 'resp_time' 
c = 'src_ip' 
d = 'cache_status' 
e = 'reply_size' 
f = 'req_method' 
g = 'req_url' 
h = 'username' 
i = 'dst_ip' 
j = 'mime_type' 
L = 'L' 

while True: 
    l = stdin.readline() 
    if l[0] == L: 
     l = l[1:].split() 
     buffer.append({ 
      a: float(l[0]), 
      b: int(l[1]), 
      c: l[2], 
      d: l[3], 
      e: int(l[4]), 
      f: l[5], 
      g: l[6], 
      h: l[7], 
      i: l[8], 
      j: l[9] 
      } 
     ) 
    if len(buffer) == 1000: 
     logs.insert(buffer) 
     buffer = [] 

    if not l: 
     break 

connection.disconnect() 
+0

當你用分析器運行它,你看到了什麼? – 2010-03-19 21:39:33

+0

確保你沒有安裝沒有C擴展名(--no_ext)的pymongo,它會產生巨大的差異。 – 2010-03-19 21:45:43

回答

0

我懷疑它可能實際上是readline()導致CPU利用率。嘗試運行相同的代碼,只需查看您提供的一些常量緩衝區即可替換readline。並嘗試運行數據庫插入註釋掉。確定其中哪一個是罪魁禍首。

1

這可能是一個更好的python分析器問題。有一些內置的Python剖析模塊,如cProfile;你可以閱讀更多關於它here

0

cpu使用情況由該活動循環給出,當爲真時。 你有多少行/分鐘?把

if len(buffer) == 1000:  
    logs.insert(buffer) 
    buffer = [] 

檢查buffer.append後

我會告訴你更多,你告訴我,你以後有多少插入弄到