线程使用比 Popen 更少的 RAM,为什么?
Threading using less RAM than Popen, why?
我有一个问题,所以我正在测试我的脚本的 RAM 使用情况,它很简单:
一个启动脚本,该脚本在 while 循环中打开 4 python 个脚本并永远循环。
我测试了两件事。一个只为每个脚本调用 Popen,一个使用线程,我发现彼此之间存在巨大差异...
带线程的脚本:
以及使用Popen打开脚本的脚本:
既然它们都做完全相同的事情,为什么 Python 线程使用的 RAM 比打开脚本的另一个线程少得多?使用线程与 Popen 的优缺点是什么?
test2:
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()
popen()
版本创建了 3 个全新的进程,每个进程 运行 都有自己独特的 Python 解释器。
threading 版本 运行 当前进程中的 3 个线程,共享其内存 space 和单一的原始 Python 解释器。
我有一个问题,所以我正在测试我的脚本的 RAM 使用情况,它很简单:
一个启动脚本,该脚本在 while 循环中打开 4 python 个脚本并永远循环。
我测试了两件事。一个只为每个脚本调用 Popen,一个使用线程,我发现彼此之间存在巨大差异...
带线程的脚本:
以及使用Popen打开脚本的脚本:
既然它们都做完全相同的事情,为什么 Python 线程使用的 RAM 比打开脚本的另一个线程少得多?使用线程与 Popen 的优缺点是什么?
test2:
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()
popen()
版本创建了 3 个全新的进程,每个进程 运行 都有自己独特的 Python 解释器。
threading 版本 运行 当前进程中的 3 个线程,共享其内存 space 和单一的原始 Python 解释器。