【问题标题】:Python: Multiprocessing running portion of code that it shouldn'tPython:不应该多处理运行的代码部分
【发布时间】:2021-06-20 16:55:31
【问题描述】:

我有点玩弄多处理和不同的数学库来计算 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")

【问题讨论】:

标签: python numpy multiprocessing mpmath


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 2013-08-11
    • 2017-01-14
    • 1970-01-01
    • 2021-08-14
    相关资源
    最近更新 更多