我正在使用 python 脚本进行大量计算。由于它受 CPU 限制,我通常使用线程模块的方法没有产生任何性能改进。
我现在试图使用多处理而不是多线程来更好地使用我的 CPU 并加速冗长的计算。
我在 stackoverflow 上找到了一些示例代码,但我没有让脚本接受多个参数。有人可以帮我解决这个问题吗?在我很确定我使用 Pool.map 之前我从未使用过这些模块。- 任何帮助表示赞赏。也欢迎使用其他方法来完成多处理。
from multiprocessing import Pool
def calculation(foo, bar, foobar, baz):
# Do a lot of calculations based on the variables
# Later the result is written to a file.
result = foo * bar * foobar * baz
print(result)
if __name__ == '__main__':
for foo in range(3):
for bar in range(5):
for baz in range(4):
for foobar in range(10):
Pool.map(calculation, foo, bar, foobar, baz)
Pool.close()
Pool.join()
Run Code Online (Sandbox Code Playgroud)