<p>我是来尝试使用<code>mmap</code>的,因为我在一个大小为几十GB的文件上使用了<code>fileh.readline()</code>,并希望使它更快。Unix <code>strace</code>实用程序似乎揭示了文件现在是以4kB的块读取的,至少strace的输出在我看来打印得很慢,我知道解析文件需要很多小时。</p>
<pre><code>$ strace -v -f -p 32495
Process 32495 attached
read(5, "blah blah blah foo bar xxxxxxxxx"..., 4096) = 4096
read(5, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"..., 4096) = 4096
read(5, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"..., 4096) = 4096
read(5, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"..., 4096) = 4096
^CProcess 32495 detached
$
</code></pre>
<p>到目前为止,这个线程是唯一解释我不应该试图<code>mmap</code>一个太大的文件的原因。我不明白为什么还没有像<code>mmap_for_dummies(filename)</code>这样的帮助函数,它可以在os.path.size(filename)内部执行,然后执行普通的<code>open(filename, 'r', buffering=10*1024*1024)</code>或执行<code>mmap.mmap(open(filename).fileno())</code>。我当然想避免自己修改滑动窗口方法,但是函数是否做一个简单的决定,是否做<code>mmap</code>对我来说就足够了。</p>
<p>最后要提的是,我仍然不清楚为什么互联网上的一些例子没有解释就提到<code>open(filename, 'rb')</code>(例如<a href="https://docs.python.org/2/library/mmap.html" rel="nofollow">https://docs.python.org/2/library/mmap.html</a>)。如果有人经常想在for循环中使用带有<code>.readline()</code>调用的文件,我不知道是应该以<code>'rb'</code>模式打开还是只以<code>'r'</code>模式打开(我想有必要保留<code>'\n'</code>)。</p>
<p>感谢您提到<code>buffering=10*1024*1024)</code>参数,这可能比更改代码以获得某种速度更有帮助。</p>