简体   繁体   English

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

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

I was sort of playing around with multiprocessing and different math libraries to calculate pi and wanted to know how much faster was it with or without multiprocessing by implementing time.perf_counter() .我有点玩弄多处理和不同的数学库来计算 pi,并想通过实现time.perf_counter()来了解使用或不使用多处理的速度有多快。 mp.Pool maps 20 threads as the same with my CPU threads count, while processing main, it also processed mp.Pool 映射 20 个线程与我的 CPU 线程数相同,在处理 main 时,它也处理了

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

which prints it 20 times.它打印了 20 次。

Result excluded print in solve:结果排除打印解决:

...
...
...

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: To fix your problem, just indent the last two lines. TLDR:要解决您的问题,只需缩进最后两行。

The multiprocessing library actually runs the entire Python script in each thread. multiprocessing库实际上在每个线程中运行整个 Python 脚本。 As an experiment run python in the same directory as the program and try importing it.作为一个实验,在与程序相同的目录中运行python并尝试导入它。 You will notice that the bottom two statements will run even though the solve function doesn't您会注意到,即使solve function 没有运行,底部的两条语句也会运行

Therefore, anything that is not in the if __name__ == "__main__": block will be run by each thread.因此,任何不在if __name__ == "__main__":块中的东西都将由每个线程运行。 The if __name__ == "__main__": statement tells Python to only run this code in the main thread. if __name__ == "__main__":语句告诉 Python 仅在主线程中运行此代码。

To solve your problem, you need to add the bottom two lines into the if statement.要解决您的问题,您需要将底部两行添加到if语句中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM