0
0

pythonから他言語の関数にリストを渡す際の速度比較

Last updated at Posted at 2024-05-10

概要

pythonから他言語で記述した関数にリストを渡す際の処理則の比較をする。今回は、他言語の関数にリストを渡すまでのpython側での実装方法の差による処理速度の比較する。比較する実装はRustの関数にリストを渡す場合を想定して用意した。

比較する実装

  1. ','.join(tokens)
  2. json.dumps(tokens)

コード

import json
import time
import matplotlib.pyplot as plt

# トークンリストの長さ
lengths = [10, 100, 1000, 10000, 100000]
# 処理時間を記録するリスト
times_comma = []
times_json = []

# 各長さに対して実験
for length in lengths:
    tokens = ['token'] * length
    # カンマ区切り文字列の時間計測
    start_time = time.time()
    for _ in range(100):
        result_comma = ','.join(tokens)
    end_time = time.time()
    times_comma.append((end_time - start_time) / 100)

    # json.dumpsの時間計測
    start_time = time.time()
    for _ in range(100):
        result_json = json.dumps(tokens)
    end_time = time.time()
    times_json.append((end_time - start_time) / 100)

# 結果のグラフ化
plt.figure(figsize=(10, 5))
plt.plot(lengths, times_comma, label='Comma-separated', marker='o')
plt.plot(lengths, times_json, label='json.dumps', marker='o')
plt.xlabel('Length of Token List')
plt.ylabel('Average Time per Operation (seconds)')
plt.title('Performance Comparison: Comma-separated vs. json.dumps')
plt.legend()
plt.grid(True)
plt.xscale('log')
plt.yscale('log')
plt.show()

結果

  1. ','.join(tokens)の方が速い

image.png

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