Search code examples
pythontimesynchronizationdelay

python execution time and delay


in that code part, im trying to collect 100 data(in the for loop) and i want if the for loop execution last less then 1 second, wait for (1-execution time) sec. how can i do that ?

thanks

while(1):               
        temparray=array('i')
        fileName = 'interval' + str(initialfreq) + '.txt'
        temp_file = open(fileName, 'wb')
    for z in range(100):
            readoff = ser.readline()                
            temp_file.write(readoff)
            readoff=int(readoff)
            temparray.append(readoff)
    print('biten aralik: '+str(initialfreq))
    general_list.write('interval'+str(initialfreq)+":    "+str(mean(temparray))+'\n')
    initialfreq= initialfreq + 1

Solution

  • Before the for loop, get the current time, as t0.

    After the for loop, get the current time again, as t1.

    Then, if t1 - t0 < 1, time.sleep(1 - (t1 - t0)).

    There are a few different choices of time objects you can use. datetime.datetime is the simplest (especially if you need to debug this later—print out a datetime and it's immediately readable to a human), if you don't need the highest precision. When you subtract two datetime objects, you get a timedelta object. So:

    t0 = datetime.datetime.now()
    for …
    t1 = datetime.datetime.now()
    td = (t1 - t0).total_seconds()
    if td < 1:
        time.sleep(1 - td)
    

    If you need better precision, there are functions in the time module that let you use better clocks that your platform supports, especially if you're on 3.3+. See the clock_gettime function in 3.3+:

    t0 = time.clock_gettime(time.CLOCK_MONOTONIC)
    for …
    t1 = time.clock_gettime(time.CLOCK_MONOTONIC)
    td = (t1 - t0) / time.clock_getres(time.CLOCK_MONOTONIC)
    # same code as above
    

    CLOCK_MONOTONIC may not be the best clock for your platform—e.g., if you have CLOCK_HIGHRES or CLOCK_MONOTONIC_RAW they will almost always be better. So, read the docs and then check what you have.

    In earlier versions (including all 2.x versions), you will have to choose between clock, perf_counter, process_time, or time, which all have different tradeoffs, and the tradeoffs are even different on different platforms (and datetime.datetime will already be at least as good as time), so no one can tell you "always use this one".