当前位置:网站首页>pytorch学习总结—运算的内存开销
pytorch学习总结—运算的内存开销
2022-06-29 08:31:00 【TJMtaotao】
前⾯面说了了,索引、 view 是不不会开辟新内存的,⽽而像 y = x + y 这样的运算是会新开内存的,然后
将 y 指向新内存。为了了演示这⼀一点,我们可以使⽤用Python⾃自带的 id 函数:如果两个实例例的ID⼀一致,那
么它们所对应的内存地址相同;反之则不不同。
x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
y = y + x
print(id(y) == id_before) # False
如果想指定结果到原来的 y 的内存,我们可以使⽤用前⾯面介绍的索引来进⾏行行替换操作。在下⾯面的例例⼦子中,
我们把 x + y 的结果通过 [:] 写进 y 对应的内存中。
x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
y[:] = y + x
print(id(y) == id_before) # True
我们还可以使⽤用运算符全名函数中的 out 参数或者⾃自加运算符 += (也即 add_() )达到上述效果,例如
torch.add(x, y, out=y) 和 y += x ( y.add_(x) )
x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
torch.add(x, y, out=y) # y += x, y.add_(x)
print(id(y) == id_before) # True
边栏推荐
猜你喜欢
随机推荐
Analysis of c voice endpoint detection (VAD) implementation process
Handwriting Redux thunk
mysql insert 时出现Deadlock死锁场景分析
What is hyperfusion? What is the difference with traditional architecture
网络安全问题
cmd进入虚拟机
微信小程序wx.navigateBack返回上一页携带参数
jar包和war包
工厂模式
Verilog expression
实例报错IOPub data rate exceeded
Unity C# 网络学习(十二)——Protobuf生成协议
记微信小程序setData动态修改字段名
Network security issues
手写VirtualDOM
微信小程序子组件向页面传值(父子组件间的通信)带源码
Uniapp wechat applet reports an error typeerror: cannot read property 'call' of undefined
Wechat applet project: wechat applet page layout
成员内部类、静态内部类、局部内部类
Member inner class, static inner class, local inner class









