我正在使用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')
这两种方法之间是否存在差异(性能或其他方面)?