擅长:python、mysql、java
<blockquote>
<p>How can it be that writing to physical disk is WAY faster than writing to the "screen" (presumably an all-RAM op), and is effectively as fast as simply dumping to the garbage with /dev/null?</p>
</blockquote>
<p>恭喜,您刚刚发现了I/O缓冲的重要性。:-)</p>
<p>磁盘<em>看起来比eem>快,因为它是高度缓冲的:所有Python的<code>write()</code>调用都在实际写入物理磁盘之前返回。(操作系统稍后会这样做,将数千个单独的写操作组合成一个大而高效的块。)</p>
<p>另一方面,终端很少或没有缓冲:每个单独的<code>print</code>/<code>write(line)</code>等待<strong>完整的</strong>写入(即显示到输出设备)完成。</p>
<p>为了使比较公平,您必须使文件测试使用与终端相同的输出缓冲区,您可以通过将示例修改为:</p>
<pre><code>fp = file("out.txt", "w", 1) # line-buffered, like stdout
[...]
for x in range(lineCount):
fp.write(line)
os.fsync(fp.fileno()) # wait for the write to actually complete
</code></pre>
<p>我在我的机器上运行了你的文件写测试,在缓冲的情况下,这里也有10万行的0.05秒。</p>
<p>但是,通过上述修改,可以无缓冲地写入,只需40秒就可以将1000行写入磁盘。我放弃了等待10万行的写作,但根据前面的推断,要花上一个小时。</p>
<p>这让终端有11秒的时间,不是吗?</p>
<p>因此,要回答你最初的问题,考虑到所有因素,向终端写信实际上非常快,而且没有太多的空间让它更快(但是各个终端做的工作量不同;请参阅Russ对此答案的评论)。</p>
<p>(您可以添加更多的写缓冲,就像磁盘I/O一样,但是在缓冲区被刷新之前,您将看不到写入终端的内容。这是一种权衡:互动性与批量效率。)</p>