【问题标题】:Matlab slow while reading 24 bit integersMatlab在读取24位整数时很慢
【发布时间】:2023-03-26 03:15:02
【问题描述】:

我发现使用带有 'int24' 选项的 Matlab 'fread' 读取以 24 位整数格式打包的数据需要很多时间。我发现,如果我在“int32”或“int16”或“int8”中读取数据,与“int24”相比,读取时间非常快。有没有更好的方法来减少读取 24 位整数数据的时间?

为了了解问题,下面给出了示例代码。

clear all; close all; clc;

% generate some data and write it as a binary file
n=10000000;
x=randn(n,1);
fp=fopen('file1.bin', 'w');
fwrite(fp, x);
fclose(fp);

% read data in 24-bit format and measure the time
% please note that the data we get here will be different from 'x'.
% The sole purpose of the code is to demonstrate the delay in reading
% 'int24'

tic;
fp=fopen('file1.bin', 'r');
y1=fread(fp, n, 'int24');
fclose(fp);
toc;


% read data in 32-bit format and measure the time

% please note that the data we get here will be different from 'x'.
% The sole purpose of the code is to demonstrate the delay in reading
% 'int24'
tic;
fp=fopen('file1.bin', 'r');
y2=fread(fp, n, 'int32');
fclose(fp);
toc;

输出内容如下: 经过的时间是 1.066489 秒。 经过的时间是 0.047944 秒。

虽然 'int32' 版本读取更多数据(32*n 位),但它比 'int24' 读取速度快 25 倍。

【问题讨论】:

  • 请提供示例代码,它还会生成一些我们可以测试的示例文件。
  • 按照 Komarov 的建议,我用示例代码更新了问题。
  • 我在MATLAB documentation on fread for a precision of int24 中找不到任何参考资料,也许这就是原因? AFAIK MATLAB 仅提供有符号和无符号的 int8int16int32int64,当然您可以反转字节顺序。您可以尝试改为阅读int8 的三元组吗?
  • @MarkMikofski 在文档中实际上是bitn。如果你运行代码,它会抛出一个警告。

标签: matlab


【解决方案1】:

通过将数据读取为无符号 8 位整数并将每组三个字节组合成等效的 24 位数字,我能够实现大约 4 倍的加速。请注意,这假定了无符号的小端值,因此您必须对其进行修改以考虑有符号或大端的数据:

>> tic;
>> fp = fopen('file1.bin', 'r');
>> y1 = fread(fp, n, 'bit24');
>> fclose(fp);
>> toc;
Elapsed time is 0.593552 seconds.

>> tic;
>> fp = fopen('file1.bin', 'r');
>> y2 = double(fread(fp, n, '*uint8'));  % This is fastest, for some reason
>> y2 = [1 256 65536]*reshape([y2; zeros(3-rem(numel(y2), 3), 1)], 3, []);
>> fclose(fp);
>> toc;
Elapsed time is 0.143388 seconds.

>> isequal(y1,y2.')  % Test for equality of the values

ans =

     1

在上面的代码中,我只是用零填充y2 以匹配y1 的大小。向量y2 也最终成为行向量而不是列向量,如果需要,可以通过简单的转置来更改。出于某种原因,fread 首先将值输出为uint8,然后将它们转换为double 比任何其他选项都快(即通过使最后一个参数'uint8''uint8=>double' 直接输出到double) .

【讨论】:

    【解决方案2】:

    首先,最好使用bitn 而不是int*

    如果将int24 更改为bit32,代码运行速度也会一样慢。所以我认为这不是你读了多少位,而是使用bitn的内部性质。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-15
      相关资源
      最近更新 更多