python中线程消耗的内存

Shu*_*mar 5 python multithreading

在这里我可以获得线程完成所需的时间。如何获取线程消耗的内存。

import threading
import time
class mythread(threading.Thread):
    def __init__(self,i,to):
        threading.Thread.__init__(self)
        self.h=i
        self.t=to
        self.st=0
        self.end=0
    def run(self):
        self.st =time.time()
        ls=[]
        for i in range(self.t):
            ls.append(i)
            time.sleep(0.002)
        self.end=time.time()
        print "total time taken by {} is {}".format(self.h,self.end-self.st)
thread1=mythread("thread1",10)
thread2=mythread("thread2",20)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
Run Code Online (Sandbox Code Playgroud)

dig*_*ter 6

(恐怕这有点没有答案,但我认为这是由于主题的性质造成的......)

线程内存使用的概念并不是一个明确定义的概念。线程共享它们的内存。唯一真正的线程本地内存是它的调用堆栈,除非您执行严格的递归操作,否则这不是有趣的部分。

“正常”内存的所有权并不那么简单。考虑这段代码:

import json
import threading
import time

data_dump = {}

class MyThread(threading.Thread):

    def __init__(self, name, limit):
        threading.Thread.__init__(self)
        self.name = name
        self.limit = limit
        data_dump[name] = []

    def run(self):
        start = time.monotonic()
        for i in range(self.limit):
            data_dump[self.name].append(str(i))
            time.sleep(0.1)
        end = time.monotonic()
        print("thread wall time: {}s".format(end-start))

t1 = MyThread(name="one", limit=10)
t2 = MyThread(name="two", limit=12)
t1.start()
t2.start()
t1.join()
t2.join()
del t1
del t2
print(json.dumps(data_dump, indent=4))
Run Code Online (Sandbox Code Playgroud)

的输出data_dump将显示线程附加(并因此分配)的所有字符串。然而,在输出时(最终print), 拥有 内存 ?两个线程都已不存在,但仍然可以访问,因此不是泄漏。线程不拥有内存(超出其调用堆栈);流程确实如此。

根据您想要如何处理这些内存消耗数字,使用 @Torxed 推荐的 cprofiler 可能会有所帮助。