gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:17:05 24 4
gpt4 key购买 nike

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

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

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 循环但以 block 的形式传递数据,它几乎与完全矢量化版本一样快,但没有内存开销:

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

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

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

关于Matlab:有没有办法加快计算数字的符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4037407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com