从Python中的二进制文件中提取特定字节

lau*_*ack 3 python mmap numpy seek fromfile

我有非常大的二进制文件,其中包含y个传感器的x个int16数据点,以及带有一些基本信息的标题.二进制文件写为y值,每个采样时间最多x个样本,然后是另一组读数,依此类推.如果我想要所有数据,我使用的numpy.fromfile()工作非常好,速度快.不过,如果我只想传感器数据或只有特定的传感器的一个子集,我现在有一个可怕的双for回路,使用file.seek(),file.read()struct.unpack()那需要永远.还有另一种方法可以在python中更快地完成这项工作吗?也许mmap()我不明白?或者只是使用整体fromfile()然后再采样?

data = numpy.empty(num_pts, sensor_indices)
for i in range(num_pts):
    for j in range(sensor_indices):
        curr_file.seek(bin_offsets[j])
        data_binary = curr_file.read(2)
        data[j][i] = struct.unpack('h', data_binary)[0]
Run Code Online (Sandbox Code Playgroud)

遵循@rrauenza的建议mmap,这是很好的信息,我编辑了代码

mm = mmap.mmap(curr_file.fileno(), 0, access=mmap.ACCESS_READ)
data = numpy.empty(num_pts,sensor_indices)
for i in range(num_pts):
    for j in range(len(sensor_indices)):
        offset += bin_offsets[j] * 2
        data[j][i] = struct.unpack('h', mm[offset:offset+2])[0]
Run Code Online (Sandbox Code Playgroud)

虽然这比以前更快,但它仍然比数量级慢几个数量级

shape = (x, y)
data = np.fromfile(file=self.curr_file, dtype=np.int16).reshape(shape)
data = data.transpose()
data = data[sensor_indices, :]
data = data[:, range(num_pts)]
Run Code Online (Sandbox Code Playgroud)

我测试了一个较小的30 Mb文件,只有16个传感器,30秒的数据.原始代码是160秒,mmap是105秒,np.fromfile并且子采样是0.33秒.

剩下的问题是 - 使用numpy.fromfile()小文件显然使用效果更好,但是会出现更大的文件问题,这些文件可能需要20 Gb,数小时或数天,最多500个传感器?

rra*_*nza 5

我肯定会尝试mmap():

https://docs.python.org/2/library/mmap.html

你读了很多里面有很多的小位的系统调用的开销,如果你打电话seek(),并read()为每一个int16要解压缩.

我写了一个小测试来证明:

#!/usr/bin/python

import mmap
import os
import struct
import sys

FILE = "/opt/tmp/random"  # dd if=/dev/random of=/tmp/random bs=1024k count=1024
SIZE = os.stat(FILE).st_size
BYTES = 2
SKIP = 10


def byfile():
    sum = 0
    with open(FILE, "r") as fd:
        for offset in range(0, SIZE/BYTES, SKIP*BYTES):
            fd.seek(offset)
            data = fd.read(BYTES)
            sum += struct.unpack('h', data)[0]
    return sum


def bymmap():
    sum = 0
    with open(FILE, "r") as fd:
        mm = mmap.mmap(fd.fileno(), 0, prot=mmap.PROT_READ)
        for offset in range(0, SIZE/BYTES, SKIP*BYTES):
            data = mm[offset:offset+BYTES]
            sum += struct.unpack('h', data)[0]
    return sum


if sys.argv[1] == 'mmap':
    print bymmap()

if sys.argv[1] == 'file':
    print byfile()
Run Code Online (Sandbox Code Playgroud)

我运行了两次方法以补偿缓存.我用过,time因为我想测量usersys时间.

结果如下:

[centos7:/tmp]$ time ./test.py file
-211990391

real    0m44.656s
user    0m35.978s
sys     0m8.697s
[centos7:/tmp]$ time ./test.py file
-211990391

real    0m43.091s
user    0m37.571s
sys     0m5.539s
[centos7:/tmp]$ time ./test.py mmap
-211990391

real    0m16.712s
user    0m15.495s
sys     0m1.227s
[centos7:/tmp]$ time ./test.py mmap
-211990391

real    0m16.942s
user    0m15.846s
sys     0m1.104s
[centos7:/tmp]$ 
Run Code Online (Sandbox Code Playgroud)

(总和-211990391只验证两个版本做同样的事情.)

查看每个版本的第二个结果,mmap()是实时的1/3.用户时间约为1/2,系统时间约为1/5.

您可能加快其速度的其他选择是:

(1)如您所述,加载整个文件.大I/O而不是小I/O 可以加快速度.但是,如果你超过系统内存,你将回退到分页,这将比mmap()(因为你必须分页)更糟糕.我在这里并不是很有希望,因为mmap已经在使用更大的I/O.

(2)并发. 也许通过多个线程并行读取文件可以加快速度,但是你可以使用Python GIL来处理. 通过避免GIL,多处理将更好地工作,您可以轻松地将数据传递回顶级处理程序.但是,这将对下一个项目,地点起作用:您可能会使您的I/O更加随机.

(3)地点.以某种方式组织您的数据(或订购您的读数),以便您的数据更加紧密. mmap()根据系统pagesize以块的形式分页文件:

>>> import mmap
>>> mmap.PAGESIZE
4096
>>> mmap.ALLOCATIONGRANULARITY
4096
>>> 
Run Code Online (Sandbox Code Playgroud)

如果您的数据更靠近(在4k块内),它将已经加载到缓冲区缓存中.

(4)更好的硬件.像SSD一样.

我确实在SSD上运行它,速度要快得多.我运行了python的配置文件,想知道解压缩是否昂贵.不是:

$ python -m cProfile test.py mmap                                                                                                                        
121679286
         26843553 function calls in 8.369 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    6.204    6.204    8.357    8.357 test.py:24(bymmap)
        1    0.012    0.012    8.369    8.369 test.py:3(<module>)
 26843546    1.700    0.000    1.700    0.000 {_struct.unpack}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.000    0.000    0.000    0.000 {method 'fileno' of 'file' objects}
        1    0.000    0.000    0.000    0.000 {open}
        1    0.000    0.000    0.000    0.000 {posix.stat}
        1    0.453    0.453    0.453    0.453 {range}
Run Code Online (Sandbox Code Playgroud)

附录:

好奇心得到了我的好处,我尝试了multiprocessing.我需要仔细查看我的分区,但是unpacks的数量(53687092)在试验中是相同的:

$ time ./test2.py 4
[(4415068.0, 13421773), (-145566705.0, 13421773), (14296671.0, 13421773), (109804332.0, 13421773)]
(-17050634.0, 53687092)

real    0m5.629s
user    0m17.756s
sys     0m0.066s
$ time ./test2.py 1
[(264140374.0, 53687092)]
(264140374.0, 53687092)

real    0m13.246s
user    0m13.175s
sys     0m0.060s
Run Code Online (Sandbox Code Playgroud)

码:

#!/usr/bin/python

import functools
import multiprocessing
import mmap
import os
import struct
import sys

FILE = "/tmp/random"  # dd if=/dev/random of=/tmp/random bs=1024k count=1024
SIZE = os.stat(FILE).st_size
BYTES = 2
SKIP = 10


def bymmap(poolsize, n):
    partition = SIZE/poolsize
    initial = n * partition
    end = initial + partition
    sum = 0.0
    unpacks = 0
    with open(FILE, "r") as fd:
        mm = mmap.mmap(fd.fileno(), 0, prot=mmap.PROT_READ)
        for offset in xrange(initial, end, SKIP*BYTES):
            data = mm[offset:offset+BYTES]
            sum += struct.unpack('h', data)[0]
            unpacks += 1
    return (sum, unpacks)


poolsize = int(sys.argv[1])
pool = multiprocessing.Pool(poolsize)
results = pool.map(functools.partial(bymmap, poolsize), range(0, poolsize))
print results
print reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), results)
Run Code Online (Sandbox Code Playgroud)