0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

プログラムを効率的に実行する仕組み「バッファリング」について

Last updated at Posted at 2025-02-02

この記事について

標準入出力を使用したパイプ処理を実行しようとしたところ、バッファリングの影響で処理が途中で止まってしまいました。
バッファリングについての知識がなかったので調べたことをまとめます。

バッファリングとは

データを即座に処理せず、一時的に貯めておく仕組みのこと。

プログラムに比較的遅い処理(画面出力やファイルへの書き込み等)が含まれる場合、
これらのデータを一時的にバッファに貯め、ある程度貯まったらまとめて出力や書き込みを行うことで効率的に処理を進める。

バッファリングの例

メール送信

1通ごとにメール送信をするとその度に手間や時間がかかるため、複数メールを一括で送信する。

pythonのprint()

Pythonでprint()を使用すると、すぐに画面に表示されないことがあります。これは、出力がバッファにためられているからです。

python
import time

print("このメッセージは遅れて表示される可能性があります...", end="")
time.sleep(5)
print(" 完了!")

上記のコードを実行すると、最初のメッセージが5秒後にまとめて表示されることがあります。

pythonでバッファリングを無効化する方法

flush=Trueを使用

print()関数にflush=Trueを指定すると、バッファを無視して即座に出力されます。
print("これは即座に表示されます!", flush=True)

Pythonをアンバッファードモードで実行

ターミナル実行時に、Pythonをアンバッファードモードで実行することで、全ての出力のバッファリングを無効化できます。
python -u ファイル名.py

sys.stdout.reconfigureを使用

すべてのprint()出力を行単位でバッファ解放することも可能です。

python
import sys
sys.stdout.reconfigure(line_buffering=True)

参考

Python Official Documentation - Output Buffering

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?