Matlab:有没有办法加快计算数字的符号?

时间:2010-10-27 20:28:33

标签: matlab

当程序数量非常大时,程序中的瓶颈是计算数组中所有数字的数字符号。我展示了我在下面尝试过的两种方法,两种方法都有类似的结果。我有16GB的RAM,阵列占用约5GB。我看到的问题是签名功能占用了大量的RAM +虚拟内存。任何人都知道一种方法来减少内存需求并加快将数组输入的符号放入数组输出的过程(见下文)?

对if或switch命令使用for循环不会耗尽内存,但需要一个小时才能完成(太长时间)。

size = 1e9; % size of large array (just an example, could be larger)
output = int8(zeros(size,1)-1); % preallocate to -1
input = single(rand(size,1));   % create random array between 0 and 1
scalar = single(0.5); % just a scalar number, set to 0.5 (midpoint) for example

% approach 1 (comment out when using approach 2)
output = int8(sign(input - scalar));  % this line of code uses a ton of RAM and virtual memory

% approach 2
output(input>scalar) = 1;            % this line of code uses a ton of RAM and virtual memory
output(input==scalar) = 0;           % this line of code uses a ton of RAM and virtual memory

提前感谢任何建议。

2 个答案:

答案 0 :(得分:6)

如果使用for循环但是以块的形式传递数据,它几乎与完全矢量化版本一样快,但没有内存开销:

chunkSize = 1e7;
for start=1:chunkSize:size
    stop = min(start+chunkSize, size);
    output(start:stop) = int8(sign(input(start:stop)-scalar));
end

此外,您的初始化代码正在创建双精度数组,然后将它们转换为单/整数数组。您可以通过执行以下操作来节省一些临时内存使用量(和时间):

input = rand(size, 1, 'single');
output = zeros(size, 1, 'int8') - 1;

答案 1 :(得分:1)

sign可能会间歇性地将输入转换为双倍。

无论如何,如果output为1表示正数,0表示负数或零,则可以尝试

siz = 1e9; %# do not use 'size' as a variable, since it's an important function
input = rand(siz,1,'single'); %# this directly creates a single array
scalar = single(0.5);
output = input>scalar;

修改的 实际上,即使是这个解决方案,我也看到内存使用率出现短暂上升。也许这与多线程有关?无论如何,速度问题来自于你开始分页这一事实,这会使一切都变慢。

相关问题