最近在学习taichi,想了解taichi的内存管理机制,官网文档有提到:ti.root 具有自动管理内存分配和回收的能力
。但我想知道具体机制是什么样的?
我用一个简单的代码测试自动内存回收,但内存直到耗尽也没有触发taichi的自动内存回收,为什么?
相关代码:
def test():
ti.init(arch=ti.gpu, kernel_profiler=True,
device_memory_fraction=0.9, debug=True)
h = 2160
w = 3840
img = np.linspace(0, 2 ** 8, w*h, endpoint=False).reshape(h, w)
pic = ti.field(dtype=ti.float64, shape=(h, w))
pic.from_numpy(img)
def _taichi_wrapper(pic):
res1 = ti.field(dtype=ti.float64, shape=pic.shape)
inc(pic, res1)
res2 = ti.field(dtype=ti.float64, shape=pic.shape)
inc(res2, res1)
return res2
for i in range(100):
print(f"test {i}")
time.sleep(0.1)
# res1 = ti.field(dtype=ti.float64, shape=(h, w))
# inc(pic, res1)
# res2 = ti.field(dtype=ti.float64, shape=(h, w))
# inc(res2, res1)
res2 = _taichi_wrapper(pic)
pic = res2
print(res2[0, 0])
time.sleep(3)
而如果是用numpy array,不用taichi field,是可以触发局部变量的自动回收的,numpy代码:
def test4():
h = 2160
w = 3840
img = np.linspace(0, 2 ** 8, w*h, endpoint=False).reshape(h, w)
# res_all = []
for i in range(100):
time.sleep(1)
res = np.array(img)
res = img + 1
img = res
# res_all.append(res)
print(f"test {i}: res={res[0, 0]}")
time.sleep(3)