2014-02-05 6 views
1

최근 파이썬 스크립트가 너무 많은 CPU를 사용하여 (분명히 스크립트가 몇 시간 동안 전체 코어를 사용하고 있었기 때문에) 내 vps에서 내게 알려졌습니다.너무 많은 CPU를 사용하는 간단한 파이썬 스크립트

class Tweet(): 

    def __init__(self, json): 

     self.user = {"id" : json.get('user').get('id_str'), "name" : json.get('user').get('name')} 
     self.timeStamp = datetime.datetime.strptime(json.get('created_at'), '%a %b %d %H:%M:%S %z %Y') 
     self.coordinates = json.get('coordinates') 
     self.tweet = { 
         "id" : json.get('id_str'), 
         "text" : json.get('text').split('#')[0], 
         "entities" : json.get('entities'), 
         "place" : json.get('place') 
        } 

     self.favourite = json.get('favorite_count') 
     self.reTweet = json.get('retweet_count') 

을 그것도 있습니다

내 스크립트

def on_success(self, data): 

    if 'text' in data: 
     self.counter += 1 
     self.tweetDatabase.save(Tweet(data)) 

     #we only want to commit when we have a batch 
     if self.counter >= 1000: 
      print("{0}: commiting {1} tweets".format(datetime.now(), self.counter)) 
      self.counter = 0 
      self.tweetDatabase.commit() 

트윗 작업이 내가 필요하지 않은 트윗에 대한 메타 데이터를 버려야하는 것입니다 클래스입니다 트윗을 스트리밍 할 twython 라이브러리를 사용하여 객체의 초소형 문자열 표현을 반환하는 __str__ 메서드

tweetDatabase.commit()은 파일에 트윗을 저장하는 반면 그는 단지 목록에 트윗을 저장 tweetDatabase.Save() :

def save(self, tweet): 
    self.tweets.append(tweet.__str__()) 

def commit(self): 
    with open(self.path, mode='a', encoding='utf-8') as f: 
     f.write('\n'.join(self.tweets)) 

    self.tweets = [] 

뭐죠 CPU를 낮게 유지하는 가장 좋은 방법? 내가 잠을 자면 프로그램이 twitters api를 듣지 않고 보낸 시간이기 때문에 나는 짹짹을 잃을 것입니다. 이것에도 불구하고 프로그램이 파일에 쓴 후에 잠시 동안 시도했다 그러나 이것은 CPU를 가져올 아무것도하지 않았다. 1000 개의 트윗을 파일로 저장하는 기록은 분당 1 회 이상입니다.

많은 감사

+0

코드를 프로파일 링하고 핫스팟이 어디에 있는지 찾아야합니다. 아마 여기에 일반 텍스트 파일 대신에 DBMS가 필요합니다 ... –

+1

빠른 JIT를 제공하는 PyPy로 전환하려고 할 수 있습니다. – nodakai

답변

1

on_success()를 먼저 커밋해야하는지 확인해보십시오. 그런 다음 트윗에 저장할 데이터가 있는지 확인하십시오. 또한 self.counter 변수에서 경쟁 조건을 고려할 수도 있으며, 아마도 mutex 나 비슷한 것으로 wrapped되어야 할 self.count에 대한 업데이트가 있어야합니다.

1

당신은

import cProfile 
command = """<whatever line that starts your program>""" 
cProfile.runctx(command, globals(), locals(), filename="OpenGLContext.profile") 

으로 프로그램을 프로파일 링하고 RunSnakeRun으로 OpenGLContext.profile를 보는 시도 할 수 있습니다 (http://www.vrplumber.com/programming/runsnakerun/)

블록이 더 큰, 더 많은 CPU 시간 그 함수가 필요합니다. 이렇게하면 프로그램의 어느 부분이 많은 CPU를 사용하고 있는지 정확히 알 수 있습니다.