Search code examples
pythonpython-2.7twistedtwisted.internet

CPU usage at the time of starting twisted reactor


I am monitoring CPU usage of python script which contains following code

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

I am using ps command to get CPU usage(in percentage)

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

and condition is that it should not use CPU greater than 5%. But as soon as I executes the script, CPU usage goes to some 16% to 20%. After that, in 3 or 4 seconds it comes down to 1% or 2%. My question is, Why CPU usage increases to 16% to 20% in the beginning? I observed that when reactor starts running, CPU usage increases for some time. After that, it hardly uses CPU(0.3% to 0.4%) in my case.


Solution

  • Starting up the Python interpreter, reading all of Twisted's bytecode into memory, and setting up the code data structures associated with launching a Python process takes a little time.

    For me, the numbers are closer to 3% than 20%, but running your scripts I did see an observable CPU blip. (I am not sure what kind of computer you're using, perhaps it is very underpowered.)

    Starting the reactor itself is not very expensive, though. You can see this by modifying your program to pause after importing, but before starting the reactor, like so:

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

    If your machine is similar to mine, you should see a blip before you hit enter, but then if you continue to watch it, you should see nothing.