【问题标题】:Threading using less RAM than Popen, why?线程使用比 Popen 更少的 RAM,为什么?
【发布时间】:2020-10-23 23:08:21
【问题描述】:

我有一个问题,所以我正在测试我的脚本的 RAM 使用情况,它很简单:

一个启动脚本,该脚本在一个while循环中打开4个python脚本并永远循环。

我测试了两件事。一个只为每个脚本调用 Popen,另一个使用线程,我发现彼此之间存在巨大差异......

带线程的脚本:

还有一个使用 Popen 打开脚本的脚本:

既然它们都做完全相同的事情,为什么 Python 线程使用的 RAM 比打开脚本的另一个要少得多?使用 threading 与 Popen 的优缺点是什么?

测试2:

import time


def testing():
    while True:
        test = "Helllo world"
        print(test)
        time.sleep(1)


if __name__ == '__main__':
    testing()

线程.py:

import threading

from test2 import testing

threading.Thread(target=testing()).start()
threading.Thread(target=testing()).start()
threading.Thread(target=testing()).start()

打开

from subprocess import Popen

for _ in range(4):
    Popen(f"py test2.py", shell=True).communicate()

【问题讨论】:

  • 您有一个我们看不到的脚本运行着我们也看不到的其他四个脚本,您希望我们告诉您为什么其中一个使用更多 RAM?请添加您的代码的“最小完整可验证示例”。谢谢。
  • @MarkSetchell 哦,好吧,我不确定是否需要代码。我可以在一秒钟内将它添加到我的代码中:)

标签: python multithreading performance subprocess popen


【解决方案1】:

popen() 版本创建了 3 个全新的进程,每个进程都运行自己独特的 Python 解释器。

threading 版本在当前进程中运行 3 个线程,共享其内存空间和单个原始 Python 解释器。

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 2019-04-09
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多