gpt4 book ai didi

python - Multiprocessing.Process 运行整个脚本,而不仅仅是 python 中的目标函数

转载 作者:行者123 更新时间:2023-12-05 06:00:45 25 4
gpt4 key购买 nike

我有一个简单的示例脚本,它使用多处理来执行一个非常简单的函数并返回进程所有部分的运行时。该脚本是完全可重现的,看起来是这样的:

import time
start_time = time.perf_counter()

import multiprocessing
print(f'Libraries loaded: {round(time.perf_counter()-start_time,2)} sec')
start_time = time.perf_counter()


def test():
print('Sleeping 1 sec')
time.sleep(1)
print('Done Sleeping')

print(f'Functions loaded: {round(time.perf_counter()-start_time,2)} sec')
start_time = time.perf_counter()


if __name__ == '__main__':
p1 = multiprocessing.Process(target=test)
p2 = multiprocessing.Process(target=test)
p1.start()
p2.start()
p1.join()
p2.join()

finish = time.perf_counter()
print(f'Multiprocessing finished in {round(finish - start_time, 2)} sec')

脚本的输出如下所示:

Libraries loaded: 0.03 sec
Functions loaded: 0.0 sec
Libraries loaded: 0.0 sec
Functions loaded: 0.0 sec
Sleeping 1 sec
Libraries loaded: 0.0 sec
Functions loaded: 0.0 sec
Sleeping 1 sec
Done SleepingDone Sleeping

Multiprocessing finished in 1.12 sec

Process finished with exit code 0

如您所见,虽然多进程并行运行,但它们每次都运行整个脚本,而不是只执行目标函数 test。因此,该脚本完全不必要地运行了两次,我不明白为什么。

谁能给我解释一下吗?

谢谢

最佳答案

这样做:

if __name__ == "__main__":
<execute main thread here>

在主线程中创建进程。新进程不会调用整个脚本,因为您只允许线程调用整个进程。

关于python - Multiprocessing.Process 运行整个脚本,而不仅仅是 python 中的目标函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67471891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com