我有三个函数,每个函数返回一个列表。问题是运行每个函数大约需要20-30秒。因此,运行整个脚本最终需要大约2分钟。
我想使用多处理或多线程(以更容易实现的方式)让所有三个函数同时运行。
我遇到的另一个障碍是,我不知道如何从每个功能中返回列表。
def main():
masterlist = get_crs_in_snow()
noop_crs = get_noops_in_snow()
made_crs = get_crs_in_git()
# take the prod master list in SNOW, subtract what's been made or is in the noop list
create_me = [obj for obj in masterlist if obj not in made_crs and obj not in noop_crs]
print "There are {0} crs in Service Now not in Ansible".format(len(create_me))
for cr in create_me:
print str(cr[0]),
if __name__ == '__main__':
main()
我想通过多线程或多处理以下行我可以在运行时获得一些重大改进:
masterlist = get_crs_in_snow()
noop_crs = get_noops_in_snow()
made_crs = get_crs_in_git()
如何同时运行这三个功能?
答案 0 :(得分:1)
这是完全未经测试的,因为我没有其他代码,但它可能会让你知道可以做些什么。我已将您的代码调整为多处理模式:
from multiprocessing import Pool
def dispatcher(n):
if n == 0:
return get_crs_in_snow()
if n == 1:
return get_noops_in_snow()
if n == 2:
return get_crs_in_git()
def main():
pool = Pool(processes=3)
v = pool.map(dispatcher, range(3))
masterlist = v[0]
noop_crs = v[1]
made_crs = v[2]
# take the prod master list in SNOW, subtract what's been made or is in the noop list
create_me = [obj for obj in masterlist if obj not in made_crs and obj not in noop_crs]
print "There are {0} crs in Service Now not in Ansible".format(len(create_me))
for cr in create_me:
print str(cr[0]),
if __name__ == '__main__':
main()
答案 1 :(得分:0)
尝试使用线程库。
import threading
threading.Thread(target=get_crs_in_snow).start()
threading.Thread(target=get_noops_in_snow).start()
threading.Thread(target=get_crs_in_git).start()
至于获取它们的返回值,你可以将调用包装在某些类函数中,并让它们将结果保存到成员变量中。或者,您可以将调用包装在一些本地函数中,并简单地将可变对象(列表或字典)传递给函数,并让函数修改该可变对象。
或者,正如其他人所说,multiprocessing可能是做你想做的事情的好方法。