Reading a structured binary file with numpy: fromfile vs. read & frombuffer

Viewed 1542

I’m reading a binary file using numpy and wondering whether I should use repeated calls to numpy.fromfile or reading from the file manually and calling 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')

Is there a difference (performance or otherwise) between these two methods?

0 Answers
Related