单进程的Python多处理速度

标签 python performance multiprocessing pool ptvs

我发现 python 多处理的一些行为我很难理解。 使用 Pool 时,即使它是单个进程,它的执行速度也会快得多。

这是为什么呢?多处理是否以某种方式优化了代码?

import time
from multiprocessing import Pool


fib_input = [24] * 10

def fib(n):
    if n in [0,1]:
        return 1
    return fib(n-1)+fib(n-2)


def main1():
    with Pool(processes=1) as p:
        results = p.map(fib, fib_input)
    print (results)


def main2():
    results = list(map(fib, fib_input))
    print (results)


if __name__ == "__main__":
    start_time = time.time()
    main1()
    print("--- %s seconds ---" % (time.time() - start_time))

    start_time = time.time()
    main2()
    print("--- %s seconds ---" % (time.time() - start_time))

输出:

[75025, 75025, 75025, 75025, 75025, 75025, 75025, 75025, 75025, 75025]
--- 0.47702741622924805 seconds ---
[75025, 75025, 75025, 75025, 75025, 75025, 75025, 75025, 75025, 75025]
--- 7.922452926635742 seconds ---

最佳答案

好的。感谢评论,我发现了我的坏处。谢谢大家!

菜鸟犯的错误。

我使用的是 Visual Studio PTVS。这就是放缓的来源。 我已将下拉菜单“build”更改为 Release,但是按 f5 仍在运行 Debug模式,而我确信这是一个干净的运行。

在外面的 cmd 中运行它就成功了。后来我发现 ctrl-f5 也可以在不调试的情况下启动。

感谢您的帮助。

关于单进程的Python多处理速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36026989/

相关文章:

python - 用于生产的 Gunicorn max_requests

python - 重命名 pandas hdfstore 中的表

python - 从大字典中弹出 N 项的最快方法

java - C# 中子字符串的实现及其使用的算法是什么?

javascript - 如何将 InMemoryUploadedFile 上传到我的 S3 存储桶?

python - 移植到旧版本;语法问题

performance - 当我为DATE列传递java.sql.Timestamp时,为什么Oracle这么慢?

Python 多处理在绘图期间挂起

Python - 如何在不阻塞线程的情况下使用 FastAPI 和 uvicorn.run?

python-3.x - 使用cuda进行多处理