【问题标题】:CPU usage at the time of starting twisted reactor启动扭曲反应器时的 CPU 使用率
【发布时间】:2015-05-04 04:47:40
【问题描述】:

我正在监控包含以下代码的 python 脚本的 CPU 使用率

from twisted.internet import reactor, task
def fun():
    print "I don't know why CPU usage increases in the beginning"
lc = task.LoopingCall(fun)
lc.start(10)
reactor.run()

我正在使用 ps 命令获取 CPU 使用率(百分比)

ps aux|grep <script_name>|grep -v grep|awk '{print $3}'

并且条件是它不应该使用超过 5% 的 CPU。 但是一旦我执行脚本,CPU 使用率就会达到 16% 到 20%。 之后,在 3 或 4 秒内下降到 1% 或 2%。 我的问题是,为什么一开始 CPU 使用率会增加到 16% 到 20%? 我观察到当 reactor 开始运行时,CPU 使用率会增加一段时间。之后,在我的情况下,它几乎不使用 CPU(0.3% 到 0.4%)。

【问题讨论】:

    标签: python python-2.7 twisted twisted.internet


    【解决方案1】:

    启动 Python 解释器,将 Twisted 的所有字节码读入内存,并设置与启动 Python 进程相关的代码数据结构需要一点时间。

    对我来说,这个数字比 20% 更接近 3%,但是在运行您的脚本时,我确实看到了可观察到的 CPU 故障。 (我不知道你用的是什么类型的电脑,可能是动力不足。)

    不过,启动反应堆本身并不昂贵。您可以通过将程序修改为在导入后但在启动反应器之前暂停来查看这一点,如下所示:

    from twisted.internet import reactor, task
    def fun():
        print("I don't know why CPU usage increases in the beginning")
    lc = task.LoopingCall(fun)
    raw_input("Hit Enter To Start The Reactor:")
    lc.start(10)
    reactor.run()
    

    如果您的机器与我的相似,您应该在按 Enter 之前看到一个光点,但是如果您继续观看它,您应该什么也看不到。

    【讨论】:

    • 我修改了您的性能监控脚本,如下所示:while sleep 1s; do ps aux|grep stack_overflow_script.py|grep -v grep|awk '{print $3}'; done,以便随着时间的推移我可以看到时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 2018-03-02
    • 1970-01-01
    • 2013-01-16
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多