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

Michael Janssen Janssen at rz.uni-frankfurt.de
Sun Mar 21 07:24:38 EST 2004


On Sun, 21 Mar 2004, Dave S wrote:

> 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.
> 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.
>
> Is there an elegant way round this?

of course you can compute the time the function actually has used:

import time
while 1:
    start = time.time()
    raw_input("stops running on ENTER: ")
    used = time.time() - start
    time.sleep( 30*60 - used ) # can get negative ...


Here's another solution:

import time
sleep_target = time.time()
while 1:
     raw_input("stops running on ENTER: ")
     sleep_target += 30*60
     sleep_time = sleep_target - time.time() # can get negative...
     time.sleep(sleep_time)


this reduces the need of a time.time call to one and with
precalculated sleep_targets you can set them to a nice value
(running a job every half hour each 00 and 30 min) which is good in
some applications.

Both ways will throw an Exception when the function runs longer than
the intervall and sleep is instructed to run for a negative time.
This must be catched, when your python-bash should be as good as the
real bash ;-)

Did I understand you right, that you want to "write a Python
equivalent of the bash prog"? Awefull. Or just an equivalent of this
bash snipplet?

Michael



More information about the Tutor mailing list