相关疑难解决方法(0)

为什么打印到stdout这么慢?可以加速吗?

我一直对使用print语句输出到终端需要多长时间感到惊讶/沮丧.在最近的一些令人痛苦的缓慢记录之后,我决定调查它并且非常惊讶地发现几乎所有花费的时间都在等待终端处理结果.

能以某种方式加速写入stdout吗?

我写了一个脚本(print_timer.py在这个问题的底部),比较写入100k行到stdout,文件和stdout重定向到的时间/dev/null.这是时间结果:

$ python print_timer.py
this is a test
this is a test
<snipped 99997 lines>
this is a test
-----
timing summary (100k lines each)
-----
print                         :11.950 s
write to file (+ fsync)       : 0.122 s
print with stdout = /dev/null : 0.050 s
Run Code Online (Sandbox Code Playgroud)

哇.为了确保python不在幕后做某事,比如认识到我将stdout重新分配给/ dev/null或其他东西,我在脚本之外进行了重定向...

$ python print_timer.py > /dev/null
-----
timing summary (100k lines each)
-----
print                         : 0.053 s
write to file (+fsync)        : 0.108 s
print with …
Run Code Online (Sandbox Code Playgroud)

python linux printing stdout tty

159
推荐指数
3
解决办法
5万
查看次数

标签 统计

linux ×1

printing ×1

python ×1

stdout ×1

tty ×1