首页 > 解决方案 > 在python中并行运行两个函数并将一个函数返回的参数作为参数传递给另一个函数

问题描述

我已经实现了一个采样器和一个时钟。我想并行运行采样器和时钟,同时我希望采样器返回时钟的结束时间,以便时钟运行这么长时间。这两个函数位于其他模块中,并且正在从其他模块中调用。

时钟代码:

def clock_generator(self, freq, end_time):

    time_period = 1 / (freq)
    clock = 0
    while time.time<end_time:
        clock = 1
        time.sleep(((time_period) / 2))
        clock = 0
        time.sleep(((time_period) / 2))

采样器代码:

 def data_sample(self, path, result_file_name, time_index, formatted_data, time_period):

    start_time = time.time()

    """perform few operations"""

    end_time = time.time()
    return end_time

标签: python

解决方案


按照上面的说明“我想同时运行数据采样器和时钟,但我希望时钟只运行到数据采样器运行,因此,我想将结束时间从数据采样器发送到时钟”:

有比并行运行另一个进程更好的方法(取决于您为什么需要在不同功能中使用时钟)。这是一种方法:

from time import time, sleep


class Clock:

  def __init__(self, freq):
    self.period = 1./freq

  def start(self):
    self.start = time()
    return self.start

  def getElapsed(self):
    return time() - self.start

  def getTick(self):
    elapsed = self.getElapsed();
    return int((elapsed/self.period) % 2)    # feel free to negate this condition

  def stop(self):
    self.end = time()
    return self.end


def data_sample():

    clock = Clock(5)
    print(clock.start())

    """perform few operations"""    # can call clock.getTick() here

    end = clock.stop()
    print(end)
    return end

data_sample()

推荐阅读