python - 在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
解决方案
按照上面的说明“我想同时运行数据采样器和时钟,但我希望时钟只运行到数据采样器运行,因此,我想将结束时间从数据采样器发送到时钟”:
有比并行运行另一个进程更好的方法(取决于您为什么需要在不同功能中使用时钟)。这是一种方法:
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()
推荐阅读
- c++ - C ++“相同字母”代码无法正常工作
- mongodb - 为什么使用 docker compose 运行时,MongoDB 的更新请求非常慢?
- bash - 使用 bash shell 命令从另一个文件的列中替换文件中的值列的最快方法?
- javascript - 无法将 html 元素周围的代理传递给 appendChild
- r - Jags:运行时错误:无法将节点插入 mu[1:30]。尺寸不匹配
- android - 我可以在 android studio 中为数据库使用所有 SQL 命令吗?
- javascript - 动态选择导轨
- javascript - 如何在 React (Hooks) 中从数组状态中删除元素
- php - PHP Mailer - 454 TLS 连接失败
- python - 如何从多个子流程公开普罗米修斯指标?