我想知道在尝试使用 MATLAB 的写时复制(惰性复制)机制从元胞数组中的多个元胞链接同一个大矩阵时,是否有办法查看我做的事情是否正确.
例如:
img = randn(500);
[dx,dy] = gradient(img);
S = cell(2,2);
S{1,1} = dx.^2;
S{2,2} = dy.^2;
S{1,2} = dx.*dy;
S{2,1} = S{1,2}; % should be a reference, as long as not modified
但是看看 whos
的输出:
>> whos
Name Size Bytes Class Attributes
S 2x2 8000448 cell
dx 500x500 2000000 double
dy 500x500 2000000 double
img 500x500 2000000 double
我希望看到 S
占用 6 MB,而不是 8 MB。
有没有办法验证程序中没有错误并且这两个单元格最后仍然引用同一个数组?
我知道函数 memory
, 但遗憾的是它只适用于 Windows 平台(我在 MacOS 上)。
最佳答案
验证两个特定数组是否实际共享数据的一种可能解决方案是使用从 Yair's Undocumented MATLAB Blog 修改的以下 MEX 文件:
#include "mex.h"
#include <cstdint>
void mexFunction( int /*nlhs*/, mxArray* plhs[], int nrhs, mxArray const* prhs[]) {
if (nrhs < 1) mexErrMsgTxt("One input required.");
plhs[0] = mxCreateNumericMatrix(1, 1, mxUINT64_CLASS, mxREAL);
std::uint64_t* out = static_cast<std::uint64_t*>(mxGetData(plhs[0]));
out[0] = reinterpret_cast<std::uint64_t>(mxGetData(prhs[0]));
}
将其保存为 getaddr.cpp
并编译
mex getaddr.cpp
允许进行以下测试:
img = randn(500);
[dx,dy] = gradient(img);
S = cell(2,2);
S{1,1} = dx.^2;
S{2,2} = dy.^2;
S{1,2} = dx.*dy;
S{2,1} = S{1,2}; % should be a reference, as long as not modified
assert(getaddr(S{1,2}) == getaddr(S{2,1}))
这与获取结构 S
实际使用的内存的摘要(我仍然认为这很有用)不同,但它确实允许验证内存是否共享。
关于matlab - 如何查看 MATLAB 中变量使用的实际内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50073860/