こんにちは、JS2IIUです。ふと疑問に思ったことを検証してみました。今回もよろしくお願いします。
Pythonで出力処理を行う際、loggingモジュールを使用する方法と、単純にprint関数を使用する方法があります。この2つの方法における処理速度に差があるのか、またファイルへの出力時のパフォーマンスに違いがあるのかを検証してみました。
比較対象
- コンソール出力
loggingモジュールでのコンソール出力と、print関数によるコンソール出力の速度を比較します。 - ファイル出力
loggingモジュールでファイルにログを保存する場合と、通常のファイル書き込みによる出力速度を比較します。
検証コード
以下のコードを実行することで、各シナリオにおける処理時間を計測し、最後にすべての実行時間をまとめて表示します。
import logging
import time
# コンソール用のロガー設定
console_logger = logging.getLogger("console_logger")
console_handler = logging.StreamHandler()
console_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
console_handler.setFormatter(console_formatter)
console_logger.addHandler(console_handler)
console_logger.setLevel(logging.INFO)
# 実行時間を記録する辞書
execution_times = {}
def measure_print_console():
start_time = time.time()
for i in range(10000):
print(f"Print statement {i}")
end_time = time.time()
execution_times["Print to console"] = end_time - start_time
def measure_logging_console():
start_time = time.time()
for i in range(10000):
console_logger.info(f"Logging statement {i}")
end_time = time.time()
execution_times["Logging to console"] = end_time - start_time
def measure_file_write():
start_time = time.time()
with open("output.txt", "w") as f:
for i in range(10000):
f.write(f"File write statement {i}\n")
end_time = time.time()
execution_times["Standard file write"] = end_time - start_time
def measure_logging_file():
# ファイル用のロガー設定
file_logger = logging.getLogger("file_logger")
file_handler = logging.FileHandler("log_output.txt")
file_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
file_handler.setFormatter(file_formatter)
file_logger.addHandler(file_handler)
file_logger.setLevel(logging.INFO)
start_time = time.time()
for i in range(10000):
file_logger.info(f"Logging file statement {i}")
end_time = time.time()
execution_times["Logging to file"] = end_time - start_time
if __name__ == "__main__":
print("Starting console output comparison...")
measure_print_console()
measure_logging_console()
print("\nStarting file output comparison...")
measure_file_write()
measure_logging_file()
# 結果のまとめ表示
print("\nExecution Time Summary:")
for method, duration in execution_times.items():
print(f"{method} took: {duration:.4f} seconds")
実行結果と考察
このコードを実行すると、次のような出力結果が得られます。
Execution Time Summary:
Print to console took: 0.0260 seconds
Logging to console took: 0.1283 seconds
Standard file write took: 0.0014 seconds
Logging to file took: 0.0884 seconds
上記の結果は、実際にJS2IIUが使っているパソコンで得られた結果です。グラフ化してみます。

各実行時間の違いを分析すると、以下のような結果が得られるでしょう。
- コンソール出力(
printvslogging)loggingモジュールでは出力内容に日時やログレベルなどのメタデータが追加されるため、printよりも処理時間が長くなりやすいです。シンプルな出力にはprintが高速ですが、複雑なログが必要な場合はloggingの利便性が重要です。 - ファイル出力(標準のファイル書き込み vs
logging)
ファイル出力でも、loggingはフォーマット設定やハンドラーの追加などの設定が加わるため、単純なファイル書き込みよりも時間がかかります。ただし、ログ管理が必要なシステムではこの利便性が優位です。
まとめ
今回の検証から、以下の知見が得られました。
loggingモジュールは利便性が高いものの、print関数よりも処理速度が遅い場合がある- ファイル出力時も、
loggingによる出力が単純なファイル書き込みよりも時間がかかるが、柔軟な設定やログフォーマットの付与が可能
一般的に、ログの一貫性やエラートラッキングが重要な場面ではloggingモジュールが有利ですが、速度を優先する場面ではprintや通常のファイル書き込みが適していることが分かります。


コメント