查看单个帖子
旧 2019-12-10, 20:48   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 Matlab:有没有一种方法可以加快计算数字符号的速度?

当数组很大时,程序中的瓶颈是计算数组中所有数字的数字符号。我将在下面展示我尝试过的两种方法,两者的结果相似。我有16GB的RAM,该阵列占用〜5GB。我看到的问题是sign函数占用大量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 在此先感谢您的任何建议。



回答:

如果使用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;

更多&回答...
poster 当前离线   回复时引用此帖