Search code examples
pythontimetimertimingbenchmarking

Python timing in order to trigger specific events


In Python I would like to run a function calling a default action for 20 seconds. However, there are 5 specific timings within these 20 seconds when another function should be triggered. In order to simplify my code, I have replaced the "action" functions with simple printing commands.

Here is what I have so far - The output seems ok, in that it lasts for 10 seconds and prints the time and the default state/action. But the triggered action is missing! Is there a better/correct way to do this?

import random
import time
import numpy as np
import itertools

def uniform_min_range(a, b, n, min_dist):
    while True:
        atimes = np.random.uniform(a, b, size=n)
        np.sort(atimes)
        if np.all(np.diff(atimes) >= min_dist):
            return atimes

def timings():
    global times
    times = uniform_min_range(0, 20, 5, 1.0) 
    print 'beep times: ', times

def defaultAction():
    global start
    print 'wobble'

def triggeredAction():
    global start
    print 'actionnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn'

def main():
    global times
    timings()
    print 'beep times: ', times
    start = time.time()
    t_end = time.time() + 20   #### end after 20 seconds
    while time.time() < t_end: #### for 20 sec/ until end reached
        print str(time.time()-start)
        if (time.time()-start) == times[0] or (time.time()-start) == times[1] or (time.time()-start) == times[2] or (time.time()-start) == times[3]:
            triggeredAction()
        elif (time.time()-start) != times[0] or (time.time()-start) != times[1] or (time.time()-start) != times[2] or (time.time()-start) != times[3]:
            defaultAction()

    print "END"

main()

Solution

  • time.time() returns second since epoch as a floating point number like:

    >>> import time
    >>> time.time()
    1465572505.891256
    

    If your comparison:

    time.time()-start) == times[0]

    to time.time() isn't correct down to the microsecond (this depends on the system), then the == won't be True and you'll never get your triggeredAction().

    Do things by the second if that works for you, use: int(time.time()) and do the same for your uniform_min_range return values - assuming per second resolution is ok for you. Otherwise you'll need to introduce a range (+ or - 1s) to your triggered action check.