Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There is no function that does this, and your method is by far the fastest approach.</p> <p>I was going to suggest <code>bytearray(mmap)</code>, the <code>array.fromfile</code>, and even a homebrew <code>os.read()</code> using <code>bytearray</code> and <code>memoryview</code>, but <code>FileIO.readinto</code> is <em>screaming fast</em>.</p> <pre><code>import os import mmap, io, array import timeit fn = 'path_to_largish_file' def fd_readinto_mmap(fd, ba): m = mmap.mmap(fd, 0, access=mmap.ACCESS_READ) ba.extend(m) m.close() def fd_readinto_fio(fd, ba): with io.FileIO(fd, closefd = False) as fio: fio.readinto(ba) def fd_readinto_array(fd, ba): ar = array.array('c') sz = os.fstat(fd).st_size fp = os.fdopen(fd, 'rb') ar.fromfile(fp, sz) ba.extend(ar) def fd_readinto_mv(fd, ba): stat = os.fstat(fd) blksize = getattr(stat, 'st_blksize', 4096) bufsize = stat.st_size buf = bytearray(bufsize) m = memoryview(buf) while True: b = os.read(fd, blksize) s = len(b) if not s: break m[:s], m = b, m[s:] writtenbytes = buffer(buf, 0, bufsize-len(m)) ba.extend(writtenbytes) setup = """ from __main__ import fn, fd_readinto_mmap, fd_readinto_fio, fd_readinto_array, fd_readinto_mv, reset_fd import os openfd = lambda : os.open(fn, os.O_RDONLY) closefd = lambda fd: os.close(fd) """ reps = 2 tests = { 'fio' : "fd=openfd(); fd_readinto_fio(fd, bytearray()); closefd(fd)", 'mmap': "fd=openfd(); fd_readinto_mmap(fd, bytearray()); closefd(fd)", 'array': "fd=openfd(); fd_readinto_array(fd, bytearray());", 'mv' : "fd=openfd(); fd_readinto_mv(fd, bytearray()); closefd(fd)", } width = max(map(len, tests)) for n,t in tests.iteritems(): time = timeit.timeit(t, setup, number=reps) print ("{:%s} {}" % width).format(n, time) </code></pre> <p>On my system, <code>FileIO</code> is orders of magnitude faster. <code>FileIO.readinto</code> seems to be nearly constant-time with respect to file size, too. (Not sure how that is even possible.)</p> <pre><code>mmap 4.86922478676 array 4.19783091545 mv 7.75051403046 fio 9.29832458496e-05 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload