使用numpy读取结构化的二进制文件:fromfile vs. read&frombuffer

时间:2018-09-04 11:48:20

标签: python performance numpy binaryfiles

我正在使用numpy读取二进制文件,想知道是否应该重复调用numpy.fromfile还是手动读取文件并调用numpy.frombuffer

# Alternative 1: fromfile
with open(path, 'rb') as f:
    num = numpy.fromfile(f, 'u4', 1)[0]
    l = numpy.fromfile(f, 'u4', num)
    o = numpy.fromfile(f, 'u4', num)
    m = numpy.fromfile(f, 'f4', num)
    c = numpy.fromfile(f, '3f4', num)
    s = numpy.fromfile(f, '3u4', num)

# Alternative 2: read & frombuffer
def fread(f, fmt):
    dtype = numpy.dtype(fmt)
    return numpy.frombuffer(f.read(dtype.itemsize), dtype)[0]
with open(path, 'rb') as f:
    num = fread(f, 'u4')
    l = fread(f, f'({num},)u4')
    o = fread(f, f'({num},)u4')
    m = fread(f, f'({num},)f4')
    c = fread(f, f'({num},3)f4')
    s = fread(f, f'({num},3)u4')

这两种方法之间是否存在差异(性能或其他方面)?

0 个答案:

没有答案