使用太多cpu的简单python脚本

时间:2014-02-05 23:29:01

标签: python twython

我最近被我的vps告知,因为我的python脚本使用了太多的cpu(显然脚本正在使用整个内核几个小时)。

我的脚本使用twython库来传送推文

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()

Tweet是一个类,它的工作是丢弃关于我不需要的推文的元数据:

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')

它还有一个__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条推文刚刚超过一分钟。

非常感谢

2 个答案:

答案 0 :(得分:1)

您可以尝试使用

分析您的程序
import cProfile
command = """<whatever line that starts your program>"""
cProfile.runctx( command, globals(), locals(), filename="OpenGLContext.profile" )

然后使用RunSnakeRun(http://www.vrplumber.com/programming/runsnakerun/)查看OpenGLContext.profile

块越大,该功能占用的CPU时间越多。这将帮助您准确找到程序的哪个部分占用大量CPU

答案 1 :(得分:1)

尝试检查是否需要先在on_success()中提交。然后,检查推文是否包含您要保存的数据。您还可能想要考虑self.counter变量上的竞争条件,并且可能应该将self.count的更新包装在互斥锁或类似的东西中。

相关问题