Sai Sai - 1 year ago 67
Python Question

Run a function for a duration of 5 secs exactly every time using time.time() in python

I have defined a function record which appends value to a list named as lists for a duration of Time.Whenever I call this function for the first time it appends 19 values to lists,but when I call it second time it appends 20 values to lists even though the time parameter that I was using both the times was 1 sec.Is there any way that I could get same no of values get appended to a list when I call the function multiple times?

import time
def record(lists,Time):
print "start_time",start_time
print "time.time",time.time()

print "list",lists
print "length of list after appending",len(lists)

record(first_list,0.05)#first time
print 1
record(second_list,0.05) #second time

Answer Source

The time it takes to do something is not fixed. It takes as long as it takes. But you need both to be the same, so just make them the same by checking both. This code does the desired amount of work, and then calls time.sleep() until the remaining time block runs out. That's way better than looping and checking time() repeatedly, because looping and checking time makes the cpu work hard to do nothing. time.sleep is specifically there to avoid using the cpu.

import time

def record(mylist, duration, count):
    while len(mylist) < count:

    remaining_time = time.time() - start_time;
    time.sleep(duration - remaining_time)

print "calling first pass"
l1 = []
record(l1, 5, 100)  #second time 
actual_duration = time.time() - start_time
print "length is", len(l1), "actual time was", actual_duration

print "calling second pass"
l2 = []
record(l2, 5, 100)  #second time 
actual_duration = time.time() - start_time
print "length is", len(l2), "actual time was", actual_duration

Obviously, if you try to do more than you can in the specified time, you won't. Maybe you can return an error if that happens? If you check time() during the function you can exit early, but I would not recommend checking it too often.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download