英文:
How to use multiple methods in Python?
问题
这是我的Python代码。
NO_1、2、3、4、5都是不同的方法,但我想要同时运行它们以减少执行时间。
没有参数值。
我尝试过使用多进程,但大多数博客建议只运行一个方法多次,我找不到同时运行不同方法的方法。
是否有一种同时运行不同方法的方法?
英文:
import sys
import time
import NO_1
import NO_2
import NO_3
import NO_4
import NO_5
if __name__ == '__main__':
start = time.time()
NO_1.NO_1()
NO_2.NO_2()
NO_3.NO_3()
NO_4.NO_4()
NO_5.NO_5()
end = time.time() - start
This is my Python Code.
NO_1,2,3,4,5 are all different methods, but I want to run them simultaneously and reduce execution time.
There are no argument values.
I tried to do it with multi-processing, but most of the blogs suggested only run one method multiple times, and I couldn't find a way to run different methods simultaneously.
Is there a way to run different methods simultaneously?
答案1
得分: 1
以下是翻译好的代码部分:
import time
import multiprocessing
import NO_1
import NO_2
import NO_3
import NO_4
import NO_5
if __name__ == '__main__':
start = time.time()
processes = [
multiprocessing.Process(target=NO_1.NO_1),
multiprocessing.Process(target=NO_2.NO_2),
multiprocessing.Process(target=NO_3.NO_3),
multiprocessing.Process(target=NO_4.NO_4),
multiprocessing.Process(target=NO_5.NO_5)
]
for process in processes:
process.start()
for process in processes:
process.join()
end = time.time() - start
你可以在multiprocessing文档中查看更多信息。
英文:
Try like this:
import time
import multiprocessing
import NO_1
import NO_2
import NO_3
import NO_4
import NO_5
if __name__ == '__main__':
start = time.time()
processes = [
multiprocessing.Process(target=NO_1.NO_1),
multiprocessing.Process(target=NO_2.NO_2),
multiprocessing.Process(target=NO_3.NO_3),
multiprocessing.Process(target=NO_4.NO_4),
multiprocessing.Process(target=NO_5.NO_5)
]
for process in processes:
process.start()
for process in processes:
process.join()
end = time.time() - start
Take a look in multiprocessing documentation for more info
答案2
得分: 0
以下是翻译好的内容:
这是另一种方法,使用您找到的map
示例和一个分发例程:
import sys
import time
from multiprocessing import Pool
import NO_1
import NO_2
import NO_3
import NO_4
import NO_5
funcs = [
NO_1.NO_1,
NO_2.NO_2,
NO_3.NO_3,
NO_4.NO_4,
NO_5.NO_5
]
def dispatch(n):
funcs[n]()
if __name__ == '__main__':
start = time.time()
with Pool(5) as p:
p.map( dispatch, [0,1,2,3,4] )
end = time.time() - start
英文:
Here's another way, using the map
examples you found and a dispatch routine:
import sys
import time
from multiprocessing import Pool
import NO_1
import NO_2
import NO_3
import NO_4
import NO_5
funcs = [
NO_1.NO_1,
NO_2.NO_2,
NO_3.NO_3,
NO_4.NO_4,
NO_5.NO_5
]
def dispatch(n):
funcs[n]()
if __name__ == '__main__':
start = time.time()
with Pool(5) as p:
p.map( dispatch, [0,1,2,3,4] )
end = time.time() - start
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论