Python: 多重处理 运行 部分不应该的代码

Python: Multiprocessing running portion of code that it shouldn't

我正在尝试使用多处理和不同的数学库来计算 pi,并且想通过实施 time.perf_counter() 了解使用或不使用多处理的速度有多快。 mp.Pool 映射 20 个线程,与我的 CPU 线程数相同,在处理 main 的同时,它还处理了

etime = time.perf_counter()
print(f"Time Used: {etime - stime:0.4f}sec.\n")

打印 20 次。

解决时排除打印结果:

...
...
...

Time Used: 0.0001sec.

Time Used: 0.0001sec.

Time Used: 0.0000sec.

Time Used: 15.0268sec.
import time
import numpy as np
from mpmath import mp
import multiprocessing as mps

stime = time.perf_counter()
mp.dps = 50
accuracy = 6000000
R = 1


def solve(a):
    n = a
    theta = 360 / n
    rad = mp.radians(theta/2)
    print(n*R*mp.sin(rad))


if __name__ == "__main__":
    pool = mps.Pool(mps.cpu_count())
    pool.map(solve, range(1, accuracy))
    pool.close()
    pool.terminate()
    pool.join()


etime = time.perf_counter()
print(f"Time Used: {etime - stime:0.4f}sec.\n")

TLDR:要解决您的问题,只需缩进最后两行。

multiprocessing 库实际上 运行 是每个线程中的整个 Python 脚本。作为实验 运行 python 在与程序相同的目录中并尝试导入它。您会注意到底部的两个语句将 运行 即使 solve 函数不会

因此,任何不在 if __name__ == "__main__": 块中的内容都将被每个线程 运行。 if __name__ == "__main__": 语句告诉 Python 在主线程中仅 运行 此代码。

要解决您的问题,您需要将下面两行添加到 if 语句中。