1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
| # ====================================================
# セクション0: 必要なライブラリのインストール
# ====================================================
!pip install pandas duckdb polars dask vaex --quiet
import pandas as pd
import duckdb
import polars as pl
import dask.dataframe as dd
import vaex
import time
import psutil
import os
import gc
import matplotlib.pyplot as plt
# ====================================================
# ユーティリティ関数群
# ====================================================
def get_memory_usage_mb():
"""
現在のプロセスが使用しているメモリ(MB)を取得して返す。
"""
process = psutil.Process(os.getpid())
return process.memory_info().rss / 1024**2 # MB単位
def generate_csv(file_name, num_rows):
"""
大量のデータを一度にメモリへ保持せず、1行ずつCSVファイルに書き込む。
これにより、ファイル作成時のメモリ使用量を抑えることができる。
"""
with open(file_name, mode="w", encoding="utf-8") as f:
# ヘッダー行
f.write("id,category,value\n")
for i in range(num_rows):
category = f"cat{i % 10}"
value = i * 0.5
# CSV行として書き込み
f.write(f"{i},{category},{value}\n")
def benchmark_pandas(csv_file):
"""
pandasでのCSV読込 & groupby集計の時間とメモリ差分を計測して返す。
戻り値: (load_time, groupby_time, load_mem_diff, groupby_mem_diff, grouped_result)
"""
gc.collect()
# --- 読込 ---
mem_before_load = get_memory_usage_mb()
start_time = time.perf_counter()
df = pd.read_csv(csv_file)
load_time = time.perf_counter() - start_time
mem_after_load = get_memory_usage_mb()
load_mem_diff = mem_after_load - mem_before_load # 差分メモリ
# --- groupby ---
mem_before_groupby = get_memory_usage_mb()
start_time = time.perf_counter()
df_grouped = df.groupby("category")["value"].sum()
groupby_time = time.perf_counter() - start_time
mem_after_groupby = get_memory_usage_mb()
groupby_mem_diff = mem_after_groupby - mem_before_groupby # 差分メモリ
return load_time, groupby_time, load_mem_diff, groupby_mem_diff, df_grouped
def benchmark_duckdb(csv_file):
"""
DuckDBでのCSV読込 & groupby集計の時間とメモリ差分を計測。
戻り値: (load_time, groupby_time, load_mem_diff, groupby_mem_diff, grouped_result)
"""
gc.collect()
# --- 読込 ---
mem_before_load = get_memory_usage_mb()
start_time = time.perf_counter()
con = duckdb.connect()
con.execute(f"CREATE TABLE sample_data AS SELECT * FROM '{csv_file}'")
load_time = time.perf_counter() - start_time
mem_after_load = get_memory_usage_mb()
load_mem_diff = mem_after_load - mem_before_load
# --- groupby ---
mem_before_groupby = get_memory_usage_mb()
start_time = time.perf_counter()
df_grouped = con.execute("""
SELECT category, SUM(value) AS total_value
FROM sample_data
GROUP BY category
""").df()
groupby_time = time.perf_counter() - start_time
mem_after_groupby = get_memory_usage_mb()
groupby_mem_diff = mem_after_groupby - mem_before_groupby
return load_time, groupby_time, load_mem_diff, groupby_mem_diff, df_grouped
def benchmark_polars(csv_file):
"""
PolarsでのCSV読込 & groupby集計の時間とメモリ差分を計測して返す。
戻り値: (load_time, groupby_time, load_mem_diff, groupby_mem_diff, grouped_result)
"""
gc.collect()
# --- 読込 ---
mem_before_load = get_memory_usage_mb()
start_time = time.perf_counter()
df = pl.read_csv(csv_file)
load_time = time.perf_counter() - start_time
mem_after_load = get_memory_usage_mb()
load_mem_diff = mem_after_load - mem_before_load
# --- groupby ---
mem_before_groupby = get_memory_usage_mb()
start_time = time.perf_counter()
df_grouped = (
df
.group_by("category")
.agg([
pl.col("value").sum().alias("total_value")
])
)
groupby_time = time.perf_counter() - start_time
mem_after_groupby = get_memory_usage_mb()
groupby_mem_diff = mem_after_groupby - mem_before_groupby
return load_time, groupby_time, load_mem_diff, groupby_mem_diff, df_grouped
def benchmark_dask(csv_file):
"""
DaskでのCSV読込 & groupby集計の時間とメモリ差分を計測して返す。
戻り値: (load_time, groupby_time, load_mem_diff, groupby_mem_diff, grouped_result)
"""
gc.collect()
# --- 読込 ---
mem_before_load = get_memory_usage_mb()
start_time = time.perf_counter()
df = dd.read_csv(csv_file) # Daskの遅延読込
load_time = time.perf_counter() - start_time
mem_after_load = get_memory_usage_mb()
load_mem_diff = mem_after_load - mem_before_load
# --- groupby ---
mem_before_groupby = get_memory_usage_mb()
start_time = time.perf_counter()
df_grouped = df.groupby("category")["value"].sum().compute() # 実際の計算
groupby_time = time.perf_counter() - start_time
mem_after_groupby = get_memory_usage_mb()
groupby_mem_diff = mem_after_groupby - mem_before_groupby
return load_time, groupby_time, load_mem_diff, groupby_mem_diff, df_grouped
def benchmark_vaex(csv_file):
"""
VaexでのCSV読込 & groupby集計の時間とメモリ差分を計測して返す。
戻り値: (load_time, groupby_time, load_mem_diff, groupby_mem_diff, grouped_result)
"""
gc.collect()
# --- 読込 ---
mem_before_load = get_memory_usage_mb()
start_time = time.perf_counter()
df = vaex.from_csv(csv_file, convert=False) # オンメモリ化しない読み込み
load_time = time.perf_counter() - start_time
mem_after_load = get_memory_usage_mb()
load_mem_diff = mem_after_load - mem_before_load
# --- groupby ---
mem_before_groupby = get_memory_usage_mb()
start_time = time.perf_counter()
df_grouped = df.groupby(by="category", agg={"value": "sum"})
groupby_time = time.perf_counter() - start_time
mem_after_groupby = get_memory_usage_mb()
groupby_mem_diff = mem_after_groupby - mem_before_groupby
return load_time, groupby_time, load_mem_diff, groupby_mem_diff, df_grouped
def plot_bar_chart(results_df, x_col, y_col, title):
"""
棒グラフを表示する汎用関数
x_col: X軸に表示する列名 (Library)
y_col: Y軸に表示する列名 (Time or Memory)
"""
plt.figure(figsize=(7, 4))
plt.bar(results_df[x_col], results_df[y_col],
color=["#4c72b0", "#55a868", "#c44e52", "#8172b2", "#ccb974"])
plt.title(title)
plt.xlabel(x_col)
plt.ylabel(y_col)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# ====================================================
# セクション1: 複数パターンのデータ行数でテスト
# ====================================================
SAMPLE_SIZES = [1_000_000, 30_000_000, 50_000_000] # 行数パターン
all_results = []
for num_rows in SAMPLE_SIZES:
print(f"\n========== 処理開始: num_rows={num_rows} ==========")
# 1) CSVファイルの作成 (メモリ節約版)
csv_file = f"sample_data_{num_rows}.csv"
print(f"{num_rows} 行のサンプルCSVを作成中: {csv_file}")
start_write = time.perf_counter()
generate_csv(csv_file, num_rows)
end_write = time.perf_counter()
print(f"CSVファイル生成完了 (所要時間: {end_write - start_write:.2f}秒)")
# 2) 各ライブラリでベンチマーク
print("\n=== ベンチマーク開始 ===")
benchmarks = []
# pandas
print("\n--- pandas ---")
load_t, groupby_t, load_mem_diff, groupby_mem_diff, _ = benchmark_pandas(csv_file)
benchmarks.append(["pandas", num_rows, load_t, groupby_t, load_mem_diff, groupby_mem_diff])
# DuckDB
print("\n--- DuckDB ---")
load_t, groupby_t, load_mem_diff, groupby_mem_diff, _ = benchmark_duckdb(csv_file)
benchmarks.append(["DuckDB", num_rows, load_t, groupby_t, load_mem_diff, groupby_mem_diff])
# Polars
print("\n--- Polars ---")
load_t, groupby_t, load_mem_diff, groupby_mem_diff, _ = benchmark_polars(csv_file)
benchmarks.append(["Polars", num_rows, load_t, groupby_t, load_mem_diff, groupby_mem_diff])
# Dask
print("\n--- Dask ---")
load_t, groupby_t, load_mem_diff, groupby_mem_diff, _ = benchmark_dask(csv_file)
benchmarks.append(["Dask", num_rows, load_t, groupby_t, load_mem_diff, groupby_mem_diff])
# Vaex
print("\n--- Vaex ---")
load_t, groupby_t, load_mem_diff, groupby_mem_diff, _ = benchmark_vaex(csv_file)
benchmarks.append(["Vaex", num_rows, load_t, groupby_t, load_mem_diff, groupby_mem_diff])
print("\n=== ベンチマーク終了 ===")
# 3) 結果をDataFrame化 → グラフ表示
results_df = pd.DataFrame(
benchmarks,
columns=["Library", "Rows", "LoadTime_sec", "GroupByTime_sec", "LoadMemoryDiff_MB", "GroupByMemoryDiff_MB"]
)
print("\n=== 処理結果の比較表 ===")
print(results_df)
# --- 読込時間グラフ ---
plot_bar_chart(results_df, "Library", "LoadTime_sec", f"Read Time Comparison ({num_rows} rows)")
# --- groupby処理時間グラフ ---
plot_bar_chart(results_df, "Library", "GroupByTime_sec", f"GroupBy Time Comparison ({num_rows} rows)")
# --- 読込時のメモリ差分グラフ ---
plot_bar_chart(results_df, "Library", "LoadMemoryDiff_MB", f"Memory Diff after Load ({num_rows} rows)")
# --- groupby時のメモリ差分グラフ ---
plot_bar_chart(results_df, "Library", "GroupByMemoryDiff_MB", f"Memory Diff after GroupBy ({num_rows} rows)")
# 全結果をまとめる
all_results.extend(benchmarks)
print(f"\n========== 処理完了: num_rows={num_rows} ==========\n")
# ====================================================
# セクション2: すべての行数をまとめた結果
# ====================================================
final_results_df = pd.DataFrame(
all_results,
columns=["Library", "Rows", "LoadTime_sec", "GroupByTime_sec", "LoadMemoryDiff_MB", "GroupByMemoryDiff_MB"]
)
print("=== 全行数の結果をまとめたテーブル ===")
print(final_results_df)
|