Skip to main content
 首页 » 编程设计

python之为什么 concurrent.futures 会增加 vms 内存

2025年02月15日7zhwl

我发现当我使用 Python 的 concurrent.futures.ThreadPoolExecutor 时,vms 内存使用(由 psutil 报告)急剧增加。

In [1]: import psutil 
 
In [2]: psutil.Process().memory_info().vms / 1e6 
Out[2]: 360.636416 
 
In [3]: from concurrent.futures import ThreadPoolExecutor 
 
In [4]: e = ThreadPoolExecutor(20) 
 
In [5]: psutil.Process().memory_info().vms / 1e6 
Out[5]: 363.15136 
 
In [6]: futures = e.map(lambda x: x + 1, range(100)) 
 
In [7]: psutil.Process().memory_info().vms / 1e6 
Out[7]: 1873.580032 
 
In [8]: e.shutdown() 
 
In [9]: psutil.Process().memory_info().vms / 1e6 
Out[9]: 1722.51136 

这似乎与线程数量成正比。

请您参考如下方法:

您可能会遇到这个问题(假设您使用的是 Linux):

https://siddhesh.in/posts/malloc-per-thread-arenas-in-glibc.html

即使 RSS 没有增加太多,这也会使虚拟内存大小膨胀。

(顺便说一句,VMS 在其他情况下可能会产生误导,例如在 CUDA 中,驱动程序会扩展进程的虚拟内存空间,以便为系统中的所有 CUDA 设备创建一个统一的地址空间。)