簡體   English   中英

讀取大型二進制文件python的最有效方法是什么

[英]What is the most efficient way to read a large binary file python

我有一個大(21 GByte)文件,我想將其讀入內存,然后傳遞給一個子程序,該子程序對我透明地處理數據。 我在 Centos 6.5 上使用 python 2.6.6,所以升級操作系統或 python 不是一個選項。 目前,我正在使用

f = open(image_filename, "rb")
image_file_contents=f.read()
f.close()
transparent_subroutine ( image_file_contents )

這很慢(~15 分鍾)。 在開始讀取文件之前,我知道文件有多大,因為我調用了 os.stat( image_filename ).st_size

所以如果有意義的話,我可以預先分配一些內存。

謝謝

按照迪特里希的建議,我測量了這種 mmap 技術比對 1.7GB 輸入文件進行大讀取快 20%

from zlib import adler32 as compute_cc

n_chunk = 1024**2
crc = 0
with open( fn ) as f:
  mm = mmap.mmap( f.fileno(), 0, prot = mmap.PROT_READ, flags = mmap.MAP_PRIVATE )
  while True:
    buf = mm.read( n_chunk )
    if not buf: break
    crc = compute_crc( buf, crc )
return crc

使用發電機

def generator(file_location):

    with open(file_location, 'rb') as entry:

        for chunk in iter(lambda: entry.read(1024 * 8), b''):

            yield chunk


go_to_streaming = generator(file_location) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM