Search code examples
pythonloopstimeline

Optimization of a timeline builder function


I've got a squared signal with a frequency f, and I'm interested in the time at which the square starts.

def time_builder(f, t0=0, tf=300):
    """
    Function building the time line in ms between t0 and tf with a frequency f.
    f: Hz
    t0 and tf: ms
    """

    time = [t0]                         # /!\ time in ms
    i = 1
    while time[len(time)-1] < tf:
        if t0 + (i/f)*1000 < tf:
            time.append(t0 + (i/f)*1000)
        else:
            break
        i += 1
    return time

So this function loops between t0 and tf to create a list in which is the timing at which a square starts. I'm quite sure it's not the best way to do it, and I'd like to know how to improve it.

Thanks.


Solution

  • If I am interpreting this correct, you are looking for a list of the times of the waves, starting at t0 and ending at tf.

    def time_builder(f, t0=0, tf=300):
        """
        Function building the time line in ms between t0 and tf with a frequency f.
        f: Hz
        t0 and tf: ms
        """
        T = 1000 / f # period [ms]
        n = int( (tf - t0) / T + 0.5 ) # n integer number of wavefronts, +0.5 added for rounding consistency
        return [t0 + i*T for i in range(n)]