[Tutor] How do I get exact function call timing in Python.

Alan Gauld alan.gauld at blueyonder.co.uk
Sun Mar 21 14:00:43 EST 2004


> I am trying to write a Python equiverlant of the BASH prog ...
>
> while true; do
> myfunctioninbackground &
> sleep "30m"
> done
>
> So that "myfunctioninbackground" is executed every 30mins on the
dot, no
> matter how long the function takes to execute.

OK, lets understand the shell solution first.

What happens is that you start a command in background mode
then pause your loop. The background job could run for a few
seconds, minutes or hours. It doesn't matter You will always
launch a new copy every 30 minutes.

> So far I have ...
>
> import time
> while True:
>     myfunction()
>     time.sleep(30*60)
>
> This executed "myfunction" 30 minuets after the last "myfunction"
ended.
> Not quite the same.

That's right. This os one area where Python has to get a bit
complicated to compete with the shell (unless it really is an
external command you want to execute, in which case os.system
does nicely). We need to introduce a concept called threading.

A thread is a sub process within our program which will run in
the background just like the & in shell, but requires a bit more
work to set up. More importantly you might have to watch how you
close your program down - checking that all threads have
completed first.

I suggest you read the documentation on the threads module, but
the good news is that yours is quite a simple case so we should
get something to work...

import thread
import time
import sys

def myfunc(threadName):
    for n in range(10000):
       if n % 3000 == 0:
          print "%s : %d" % (threadName, n)
    print threadName,"finished"

for n in range(5):
    name = "thread"+str(n) #thread0,thread1...thread4
    thread.start_new_thread(myfunc,(name,))  #args passed in tuple
    time.sleep(0.005)

Which on my PC gives the following output (you may need
to alter the sleep times to get similar results)

$ python threadtest.py
thread0 : 0
thread0 : 3000
thread0 : 6000
thread1 : 0
thread0 : 9000
thread0 finished
thread1 : 3000
thread2 : 0
thread1 : 6000
thread2 : 3000
thread3 : 0
thread1 : 9000
thread1 finished
thread2 : 6000
thread4 : 0
thread3 : 3000

Notice that all threads started but only threads 0 and 1 finished
before the program did. So if your function takes longer than the
sleep period you will need to check for the status of all threads
before closing.

If the function time is always less than the sleep time then life
becomes much much easier.... :-)

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list