Gar*_*uth 7 python multithreading memory-management
我写了大约50个类,用于连接和使用机械化和线程的网站.它们都同时工作,但它们并不相互依赖.所以这意味着1个类 - 1个网站 - 1个线程.它不是特别优雅的解决方案,特别是对于管理代码,因为很多代码在每个类中重复(但不足以使它成为一个类来传递参数,因为一些站点可能需要在方法中间对检索到的数据进行额外处理 - 像'登录' - 其他人可能不需要).正如我所说,它并不优雅 - 但它有效.毋庸置疑,我欢迎所有建议如何更好地编写这个,而不使用每个网站方法的1个类.添加每个类的附加功能或整体代码管理是一项艰巨的任务.
但是,我发现,每个线程占用大约8MB内存,因此使用50个正在运行的线程,我们正在考虑大约400MB的使用量.如果它在我的系统上运行我就不会有问题,但由于它在仅有1GB内存的VPS上运行,因此它开始出现问题.你能告诉我如何减少内存使用量,还是有其他方法同时使用多个站点?
我使用这个快速测试python程序来测试它是存储在我的应用程序的变量中的数据是使用内存还是其他东西.正如您在下面的代码中看到的,它只处理sleep()函数,但每个线程使用8MB内存.
from thread import start_new_thread
from time import sleep
def sleeper():
try:
while 1:
sleep(10000)
except:
if running: raise
def test():
global running
n = 0
running = True
try:
while 1:
start_new_thread(sleeper, ())
n += 1
if not (n % 50):
print n
except Exception, e:
running = False
print 'Exception raised:', e
print 'Biggest number of threads:', n
if __name__ == '__main__':
test()
Run Code Online (Sandbox Code Playgroud)
当我运行它时,输出是:
50
100
150
Exception raised: can't start new thread
Biggest number of threads: 188
Run Code Online (Sandbox Code Playgroud)
通过删除running = False行,我可以使用free -mshell中的命令测量空闲内存:
total used free shared buffers cached
Mem: 1536 1533 2 0 0 0
-/+ buffers/cache: 1533 2
Swap: 0 0 0
Run Code Online (Sandbox Code Playgroud)
通过将上述测试应用程序运行之前和期间使用的内存差除以它设法启动的最大线程数除以实际计算为什么我知道它每个线程大约需要8MB.
它可能只分配了内存,因为通过观察top,python进程只使用了大约0.6%的内存.
| 归档时间: |
|
| 查看次数: |
8567 次 |
| 最近记录: |