4

我注意到将已经完整的矩阵转换为完整的矩阵很慢:

>> tic; for k = 1:100; x = uint16(ones(10000,100)); end; toc
Elapsed time is 0.035748 seconds.
>> tic; for k = 1:100; x = uint16(uint16(ones(10000,100))); end; toc
Elapsed time is 0.034180 seconds.
>> tic; for k = 1:100; x = full(uint16(ones(10000,100))); end; toc
Elapsed time is 0.460977 seconds. %%%%% SLOW!

我也没有进行测试uint16

>> tic; for k = 1:100; x = ones(10000,100); end; toc
Elapsed time is 0.060028 seconds.
>> tic; for k = 1:100; x = full(ones(10000,100)); end; toc
Elapsed time is 0.229058 seconds. %%%%% SLOW!

一样的效果。

为什么是这样?full应该只将稀疏矩阵转换为完整矩阵。如果它已经满了,它不应该什么都不做吗?

编辑:issparse超快!我想作为 MEX,主要是内存成本?

Mac OS X 上的 MATLAB 版本 7.13.0.564 (R2011b)

4

2 回答 2

1

Disclaimer: This is my best guess about what is happening, but I don't know for sure what goes on under Matlab's hood. Update: In a comment, EitanT pointed out that my guess is most likely wrong.

I think that Matlab's JIT engine is doing optimizations in some of these cases, but not all.

When you have a loop where a variable is created but never used, the JIT engine doesn't bother creating that variable over and over. It just does it once. Anything like this will be fast:

% this calls 'ones' once
for i = 1:100, x = ones(10000,100); end

But if you create a variable and then use it, say by passing it to a function, that variable is created every time. This takes more time, obviously.

% this calls 'ones' every iteration to pass to `full`
for i = 1:100, x = full(ones(10000,100)); end
于 2013-02-26T16:30:03.953 回答
1

full works just fine.

The slow part is actually the ones(10000, 100)... here's the proof:

>> tic, for k = 1:100, x = ones(10000,100); end, toc
Elapsed time is 0.043143 seconds.

>> A = ones(10000,100);
>> tic, for k = 1:100, x = full(A); end, toc
Elapsed time is 0.000081 seconds.

full is invoked with a non-sparse matrix and runs fast, hence it is not the reason for the slowdown.

于 2013-02-26T16:12:34.107 回答