Python × Big Data × Spark × 智慧養殖
Python × PySpark 大數據效能實戰: 從 Partition、Cache、Shuffle 到 AQE, 探索百萬筆智慧養殖資料的效能最佳化
大數據系統的效能,不只是取決於 CPU 的速度, 更取決於資料如何分割、如何重複使用、 如何交換,以及如何安排運算工作。
本篇延續百萬筆智慧養殖資料與 Spark Web UI 實驗, 透過四個動手作實驗, 讓學生從觀察大數據運算, 進一步學習如何改善大數據運算效能。
一、從上一個實驗發現問題
在前一篇 Spark Web UI 實驗中, 我們成功使用 PySpark 分析一百萬筆智慧養殖模擬資料。
從這些數據可以發現, Spark 雖然已經成功完成所有分析工作, 但仍有許多值得探討的效能問題。
- 為什麼有 16 個邏輯運算資源, 原始資料卻只有 7 個 Partition?
- 為什麼約 25 MiB 的 CSV, 累計讀取量會超過 100 MiB?
- 為什麼各魚塭分組統計的 Shuffle 量較大?
- 為什麼設定 200 個 Shuffle Partitions, 實際執行的 Tasks 卻可能遠少於 200?
二、四大效能最佳化技術
決定運算工作的粒度與平行程度。
減少重複讀取與重複計算。
觀察跨 Partition 的資料移動成本。
依據執行期間的資訊調整運算計畫。
| 技術 | 主要問題 | 觀察頁面 |
|---|---|---|
| Partition | 資料如何分配? | Stages |
| Cache | 如何避免重複讀取? | Storage、Executors |
| Shuffle | 資料交換成本有多大? | Stages、SQL |
| AQE | 如何動態調整運算計畫? | SQL / DataFrame |
三、實驗環境與準備工作
沿用前一篇已經成功執行的環境。
| 項目 | 環境 |
|---|---|
| 作業系統 | Windows 10 |
| Python | 3.14 |
| Java | JDK 17 |
| Spark | 4.3.0(前次實測畫面) |
| Master | local[*] |
| Web UI | localhost:4040 |
| 資料檔案 | water_quality.csv |
建議建立以下實驗檔案:
spark_optimization/
│
├── water_quality.csv
├── spark_common.py
├── exp01_partition.py
├── exp02_cache.py
├── exp03_shuffle.py
├── exp04_aqe.py
└── exp05_benchmark.py
四個實驗共用相同的資料讀取函式及分析函式, 避免因程式內容不同而影響比較結果。
四、建立共用程式 spark_common.py
from pathlib import Path
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
CSV_PATH = Path(__file__).resolve().parent / "water_quality.csv"
SCHEMA = """
id LONG,
pond_id INT,
temperature DOUBLE,
DO DOUBLE,
pH DOUBLE
"""
def create_spark(name, master="local[*]",
shuffle_partitions=200,
aqe=True):
spark = (
SparkSession.builder
.appName(name)
.master(master)
.config("spark.ui.enabled", "true")
.config("spark.ui.port", "4040")
.config(
"spark.sql.shuffle.partitions",
str(shuffle_partitions)
)
.config(
"spark.sql.adaptive.enabled",
str(aqe).lower()
)
.getOrCreate()
)
spark.sparkContext.setLogLevel("ERROR")
print("Spark 版本:", spark.version)
print("Spark Web UI:", spark.sparkContext.uiWebUrl)
print("預設平行度:", spark.sparkContext.defaultParallelism)
return spark
def load_data(spark):
if not CSV_PATH.exists():
raise FileNotFoundError(CSV_PATH)
return spark.read.csv(
str(CSV_PATH),
header=True,
schema=SCHEMA
)
def pond_statistics(df):
return df.groupBy("pond_id").agg(
F.count("*").alias("count"),
F.avg("DO").alias("average_do"),
F.avg("temperature").alias("avg_temp"),
F.avg("pH").alias("avg_ph")
)
def global_statistics(df):
return df.agg(
F.count("*").alias("total_count"),
F.avg("DO").alias("average_do"),
F.max("DO").alias("max_do"),
F.min("DO").alias("min_do")
)
def clear_job_group(sc):
sc.setLocalProperty("spark.jobGroup.id", None)
sc.setLocalProperty("spark.job.description", None)
sc.setLocalProperty("spark.job.interruptOnCancel", None)
五、實驗一:Partition 資料分割與平行運算
5-1 什麼是 Partition?
Partition 是 Spark 將資料切分後的基本運算單位。 一個 Stage 通常會針對需要處理的每個 Partition 安排一個 Task。
Partition 太少,可能無法充分利用運算資源; Partition 太多,則可能增加 Task 排程與管理成本。
5-2 前次實測的 Partition 分布
| Partition ID | 資料筆數 |
|---|---|
| 0 | 161,739 |
| 1 | 157,567 |
| 2 | 157,556 |
| 3 | 157,551 |
| 4 | 157,563 |
| 5 | 157,561 |
| 6 | 50,463 |
| 合計 | 1,000,000 |
原始 CSV 被分割成七個 Partition, 而且各 Partition 的資料筆數不完全相同。
5-3 repartition() 與 coalesce()
| 比較項目 | repartition() | coalesce() |
|---|---|---|
| 增加 Partition | 可以 | 通常不會增加 |
| 減少 Partition | 可以 | 可以 |
| Shuffle | 通常需要 | 通常不需要完整 Shuffle |
| 資料平衡 | 通常較有利 | 可能保留不均衡情形 |
5-4 建立 exp01_partition.py
import time
from pyspark.sql import functions as F
from spark_common import (
create_spark,
load_data,
pond_statistics,
clear_job_group
)
spark = create_spark("EXP01-Partition")
sc = spark.sparkContext
try:
df = load_data(spark)
print("原始 Partition:", df.rdd.getNumPartitions())
results = []
for n in [1, 4, 8, 16, 32, 64]:
sc.setJobGroup(
f"partition-{n}",
f"Partition Experiment - {n}"
)
start = time.perf_counter()
data = df.repartition(n)
result = pond_statistics(data).collect()
elapsed = time.perf_counter() - start
results.append((n, elapsed))
print("-" * 40)
print("指定 Partition:", n)
print("魚塭統計筆數:", len(result))
print(f"執行時間:{elapsed:.3f} 秒")
print("\nPartition 效能比較")
for n, elapsed in results:
print(f"{n:3d} partitions : {elapsed:.3f} s")
# 額外觀察 16 個 Partition 的資料分布
sc.setJobGroup(
"partition-distribution",
"Partition Distribution - 16"
)
df.repartition(16).withColumn(
"partition_id",
F.spark_partition_id()
).groupBy(
"partition_id"
).count().orderBy(
"partition_id"
).show(100)
clear_job_group(sc)
input("請觀察 Spark Web UI,按 Enter 結束...")
finally:
spark.stop()
5-5 執行實驗
python -u exp01_partition.py
開啟 Spark Stages , 觀察不同 Partition 設定下的 Tasks、 Duration、Shuffle Read 與 Shuffle Write。
【插入 Partition 實驗 Stages 截圖】
圖:比較不同資料分割數量所產生的運算工作。
5-6 實驗紀錄表
| Partition | 執行時間 | Tasks | Shuffle Write |
|---|---|---|---|
| 1 | 待測 | 待測 | 待測 |
| 4 | 待測 | 待測 | 待測 |
| 8 | 待測 | 待測 | 待測 |
| 16 | 待測 | 待測 | 待測 |
| 32 | 待測 | 待測 | 待測 |
| 64 | 待測 | 待測 | 待測 |
5-7 思考問題
- Partition 數量越多,執行速度一定越快嗎?
- 16 個 Cores 是否一定要設定 16 個 Partition?
- 為什麼 repartition() 可能增加 Shuffle?
- 哪一種設定最適合目前的電腦與資料量?
六、實驗二:Cache 資料快取
6-1 為什麼需要 Cache?
前一次實驗中, 原始資料每次完整掃描約為 25.7 MiB, 但累計 Input 卻達到 102.7 MiB。
這是因為 Spark 採用 Lazy Evaluation(延遲求值)。 若沒有適當快取資料, 不同 Action 可能重新執行相同的資料讀取流程。
6-2 cache() 不會立即執行
df.cache()
上述指令只是標記 DataFrame 需要快取。 通常必須執行 Action,才會真正建立快取內容。
df.cache()
df.count()
count() 會觸發資料運算, 讓 Spark 建立快取資料。
6-3 建立 exp02_cache.py
import time
from pyspark.sql import functions as F
from spark_common import (
create_spark,
load_data,
global_statistics,
pond_statistics,
clear_job_group
)
spark = create_spark("EXP02-Cache")
sc = spark.sparkContext
df = None
def run_analysis(data):
global_statistics(data).collect()
data.filter(
F.col("DO") < 4
).count()
pond_statistics(data).collect()
data.agg(
F.avg("temperature")
).collect()
try:
df = load_data(spark)
# A:未使用 Cache
sc.setJobGroup(
"without-cache",
"A - Without Cache"
)
start = time.perf_counter()
run_analysis(df)
without_cache = time.perf_counter() - start
# B:建立 Cache
sc.setJobGroup(
"build-cache",
"B - Build Cache"
)
start = time.perf_counter()
df.cache()
df.count()
build_cache = time.perf_counter() - start
# C:使用 Cache 進行相同分析
sc.setJobGroup(
"with-cache",
"C - With Cache"
)
start = time.perf_counter()
run_analysis(df)
with_cache = time.perf_counter() - start
total_cache = build_cache + with_cache
print("=" * 50)
print("Cache 效能比較")
print("=" * 50)
print(f"未使用 Cache:{without_cache:.3f} 秒")
print(f"建立 Cache:{build_cache:.3f} 秒")
print(f"使用 Cache:{with_cache:.3f} 秒")
print(f"含建立成本:{total_cache:.3f} 秒")
if with_cache > 0:
speedup = without_cache / with_cache
print(f"快取後加速比:{speedup:.2f} 倍")
if total_cache > 0:
total_speedup = without_cache / total_cache
print(f"含建立成本加速比:{total_speedup:.2f} 倍")
print("Storage Level:", df.storageLevel)
clear_job_group(sc)
input("請觀察 Storage 頁面,按 Enter 釋放快取...")
df.unpersist(blocking=True)
input("重新整理 Storage 頁面,按 Enter 結束...")
finally:
if df is not None:
df.unpersist()
spark.stop()
6-4 執行實驗
python -u exp02_cache.py
觀察以下 Spark Web UI 頁面:
6-5 Storage 頁面觀察重點
| 項目 | 觀察意義 |
|---|---|
| RDD Name | 被快取的資料或運算結果 |
| Storage Level | 快取儲存策略 |
| Cached Partitions | 已快取的資料分割數量 |
| Fraction Cached | 快取完成比例 |
| Size in Memory | 記憶體使用量 |
| Size on Disk | 磁碟快取使用量 |
【插入建立 Cache 後的 Storage 截圖】
圖:觀察快取資料、Partition 數量及記憶體使用情形。
6-6 cache() 與 persist()
from pyspark import StorageLevel
df.persist(StorageLevel.MEMORY_ONLY)
df.persist(StorageLevel.MEMORY_AND_DISK)
df.persist(StorageLevel.DISK_ONLY)
| 策略 | 意義 |
|---|---|
| MEMORY_ONLY | 優先將資料快取於記憶體 |
| MEMORY_AND_DISK | 記憶體不足時可使用磁碟 |
| DISK_ONLY | 將快取資料儲存於磁碟 |
上述為三種替代設定,不應連續套用於同一個 已持久化的 DataFrame。 若要切換策略,應先執行 unpersist()。
6-7 實驗紀錄表
| 測試項目 | 實測時間 |
|---|---|
| 未使用 Cache | 待測 |
| 建立 Cache | 待測 |
| 使用 Cache 分析 | 待測 |
| 含建立成本的總時間 | 待測 |
| 快取記憶體使用量 | 待測 |
七、實驗三:Shuffle 資料交換成本
7-1 什麼是 Shuffle?
當 Spark 必須將相同魚塭的資料重新集中, 或進行全域排序、分組統計與資料連接時, 就可能需要跨 Partition 交換資料。 這個過程稱為 Shuffle。
依魚塭編號重新分配資料
7-2 Narrow Transformation 與 Wide Transformation
| 操作 | 是否通常需要 Shuffle |
|---|---|
| filter() | 否 |
| select() | 否 |
| withColumn() | 否 |
| groupBy() + agg() | 通常需要 |
| orderBy() | 通常需要 |
| repartition() | 通常需要 |
| join() | 視 Join 策略而定 |
Narrow Transformation 通常可以在原本的 Partition 內完成。 Wide Transformation 則可能需要跨 Partition 交換資料。
7-3 建立 exp03_shuffle.py
import time
from pyspark.sql import functions as F
from spark_common import (
create_spark,
load_data,
global_statistics,
pond_statistics,
clear_job_group
)
spark = create_spark("EXP03-Shuffle")
sc = spark.sparkContext
try:
df = load_data(spark)
# A:只有 filter 與 select
sc.setJobGroup(
"shuffle-a",
"A - Filter and Select"
)
start = time.perf_counter()
result_a = (
df.filter(F.col("DO") < 4)
.select("id", "pond_id", "DO")
)
# foreachPartition 遍歷結果,
# 避免 collect 大量原始資料到 Driver
result_a.foreachPartition(
lambda rows: sum(1 for row in rows)
)
print("A:", time.perf_counter() - start)
result_a.explain(mode="formatted")
# B:整體水質統計
sc.setJobGroup(
"shuffle-b",
"B - Global Aggregation"
)
start = time.perf_counter()
result_b = global_statistics(df)
print(result_b.collect())
print("B:", time.perf_counter() - start)
result_b.explain(mode="formatted")
# C:依魚塭進行分組統計
sc.setJobGroup(
"shuffle-c",
"C - Pond GroupBy"
)
start = time.perf_counter()
result_c = pond_statistics(df)
result_c.collect()
print("C:", time.perf_counter() - start)
result_c.explain(mode="formatted")
# D:重新分割後再進行魚塭統計
sc.setJobGroup(
"shuffle-d",
"D - Repartition and GroupBy"
)
start = time.perf_counter()
result_d = pond_statistics(
df.repartition(32)
)
result_d.collect()
print("D:", time.perf_counter() - start)
result_d.explain(mode="formatted")
clear_job_group(sc)
input("請觀察各工作 Shuffle 指標,按 Enter 結束...")
finally:
spark.stop()
7-4 執行實驗
python -u exp03_shuffle.py
開啟 Stages 與 SQL / DataFrame 頁面, 比較四項工作的 Shuffle Read、Shuffle Write, 並觀察 Physical Plan 是否出現 Exchange。
| 工作 | 預期現象 | Shuffle Write |
|---|---|---|
| A:Filter / Select | 資料過濾本身不需 Shuffle | 待測 |
| B:Global Aggregation | 交換少量局部統計結果 | 待測 |
| C:GroupBy | 依魚塭編號交換統計資料 | 待測 |
| D:Repartition + GroupBy | 可能增加額外資料交換 | 待測 |
7-5 Spark 為什麼先進行局部聚合?
假設三個 Partition 都有同一個魚塭的 DO 資料。
| Partition | DO 資料 | 局部總和 | 筆數 |
|---|---|---|---|
| P0 | 4、6、8 | 18 | 3 |
| P1 | 3、5 | 8 | 2 |
| P2 | 6、8 | 14 | 2 |
Spark 不需要將七筆原始資料全部集中, 而是可以先計算各 Partition 的總和與筆數, 再交換局部統計結果。
平均 DO = (18 + 8 + 14) / (3 + 2 + 2)
= 40 / 7
= 5.714 mg/L
當資料量增加到一百萬筆時, 先進行局部聚合便可能大幅降低 Shuffle 成本。
八、實驗四:AQE 自適應查詢執行
8-1 什麼是 AQE?
AQE 是 Adaptive Query Execution 的縮寫, 中文稱為自適應查詢執行。
傳統的查詢最佳化主要在執行前建立運算計畫。 AQE 則可以在執行過程中取得實際統計資訊, 並據此調整後續的運算策略。
8-2 AQE 的三項重要能力
8-3 為什麼 200 個 Shuffle Partitions 可能變成一個?
在前次智慧養殖實驗中, 我們看到以下執行計畫:
Exchange
hashpartitioning(pond_id, 200)
AdaptiveSparkPlan
然而在 Stages 頁面中, 最終彙整階段可能只需要一個 Task。
圖:AQE 合併 Shuffle Partitions 的概念示意, 實際合併數量由 Spark 執行計畫決定。
8-4 建立 exp04_aqe.py
import time
from spark_common import (
create_spark,
load_data,
pond_statistics,
clear_job_group
)
spark = create_spark(
"EXP04-AQE",
shuffle_partitions=200
)
sc = spark.sparkContext
try:
df = load_data(spark)
# 讓兩組測試使用相同的快取資料
df.cache()
df.count()
spark.conf.set(
"spark.sql.adaptive.coalescePartitions.enabled",
"true"
)
results = []
for enabled in [False, True]:
spark.conf.set(
"spark.sql.adaptive.enabled",
str(enabled).lower()
)
sc.setJobGroup(
f"aqe-{enabled}",
f"AQE Enabled = {enabled}"
)
# 每次重新建立 DataFrame 查詢
result = pond_statistics(df)
start = time.perf_counter()
rows = result.collect()
elapsed = time.perf_counter() - start
print("=" * 50)
print("AQE:", enabled)
print("魚塭統計筆數:", len(rows))
print(f"執行時間:{elapsed:.3f} 秒")
result.explain(mode="formatted")
results.append((enabled, elapsed))
print("\nAQE 效能比較")
for enabled, elapsed in results:
print(
f"AQE={enabled}: {elapsed:.3f} 秒"
)
clear_job_group(sc)
input("請比較 SQL 與 Stages 頁面,按 Enter 結束...")
df.unpersist()
finally:
spark.stop()
8-5 執行實驗
python -u exp04_aqe.py
進入 SQL / DataFrame 頁面, 分別點選 AQE 關閉與開啟的查詢工作。
觀察執行計畫是否出現以下資訊:
AdaptiveSparkPlan
AQEShuffleRead
coalesced
isFinalPlan=true
不同 Spark 版本可能使用不同的執行計畫節點名稱, 請以實際畫面為準。
【插入 AQE=False 執行計畫截圖】
圖:未啟用 AQE 的查詢計畫。
【插入 AQE=True 執行計畫截圖】
圖:啟用 AQE 後的查詢計畫。
8-6 實驗紀錄表
| 比較項目 | AQE 關閉 | AQE 開啟 |
|---|---|---|
| 初始 Shuffle Partitions | 200 | 200 |
| 實際 Shuffle 後 Tasks | 待測 | 待測 |
| Shuffle Write | 待測 | 待測 |
| Shuffle Read | 待測 | 待測 |
| 執行時間 | 待測 | 待測 |
| 是否出現 AdaptiveSparkPlan | 待測 | 待測 |
九、實驗五:整合效能最佳化測試
完成四個基礎實驗後, 接下來將不同效能策略整合成一個測試程式。
| 組別 | Partition | Cache | Shuffle Partitions | AQE |
|---|---|---|---|---|
| A 基準組 | 原始 | 否 | 200 | 否 |
| B | 16 | 否 | 200 | 否 |
| C | 原始 | 是 | 200 | 否 |
| D | 原始 | 否 | 16 | 否 |
| E | 原始 | 否 | 200 | 是 |
| F 整合組 | 16 | 是 | 16 | 是 |
A 到 E 主要用來比較個別設定的影響, F 則用來探索多種策略共同使用時的結果。
9-1 建立 exp05_benchmark.py
import csv
import time
import random
import statistics
from pathlib import Path
from pyspark.sql import functions as F
from spark_common import (
create_spark,
load_data,
global_statistics,
pond_statistics,
clear_job_group
)
spark = create_spark("EXP05-Benchmark")
sc = spark.sparkContext
REPEAT = 3
CONFIGS = [
("A-Baseline", None, False, 200, False),
("B-Partition", 16, False, 200, False),
("C-Cache", None, True, 200, False),
("D-Shuffle", None, False, 16, False),
("E-AQE", None, False, 200, True),
("F-Combined", 16, True, 16, True)
]
results = []
rng = random.Random(42)
def analyze(df):
summary = global_statistics(df).first()
low_do = df.filter(
F.col("DO") < 4
).count()
ponds = pond_statistics(df).collect()
avg_temp = df.agg(
F.avg("temperature")
).first()[0]
# 回傳可供正確性驗證的統計資訊
return (
summary["total_count"],
low_do,
len(ponds),
round(summary["average_do"], 8),
round(avg_temp, 8)
)
try:
# JVM 與 Spark SQL 暖機,不納入測試時間
sc.setJobGroup("warmup", "Warm-up")
spark.range(100000).count()
reference = None
for repeat in range(1, REPEAT + 1):
order = CONFIGS.copy()
rng.shuffle(order)
for name, partitions, cache, shuffle, aqe in order:
spark.catalog.clearCache()
spark.conf.set(
"spark.sql.shuffle.partitions",
str(shuffle)
)
spark.conf.set(
"spark.sql.adaptive.enabled",
str(aqe).lower()
)
sc.setJobGroup(
f"{name}-{repeat}",
f"{name} - Round {repeat}"
)
total_start = time.perf_counter()
df = load_data(spark)
if partitions is not None:
df = df.repartition(partitions)
build_time = 0.0
try:
if cache:
start = time.perf_counter()
df.cache()
df.count()
build_time = (
time.perf_counter() - start
)
start = time.perf_counter()
output = analyze(df)
query_time = (
time.perf_counter() - start
)
total_time = (
time.perf_counter() - total_start
)
if reference is None:
reference = output
if output != reference:
raise RuntimeError(
f"{name} 統計結果不一致"
)
results.append({
"experiment": name,
"round": repeat,
"partitions": (
partitions
if partitions is not None
else "original"
),
"cache": cache,
"shuffle_partitions": shuffle,
"aqe": aqe,
"build_cache_seconds": round(
build_time, 4
),
"query_seconds": round(
query_time, 4
),
"total_seconds": round(
total_time, 4
),
"total_count": output[0],
"low_do_count": output[1]
})
print(
name,
"Round", repeat,
f"Total={total_time:.3f}s",
f"Query={query_time:.3f}s"
)
finally:
if cache:
df.unpersist(blocking=True)
output_path = (
Path(__file__).resolve().parent
/ "spark_benchmark_results.csv"
)
with output_path.open(
"w",
newline="",
encoding="utf-8-sig"
) as f:
writer = csv.DictWriter(
f,
fieldnames=list(results[0].keys())
)
writer.writeheader()
writer.writerows(results)
print("=" * 60)
print("效能最佳化實驗結果:總時間中位數")
print("=" * 60)
baseline = statistics.median([
row["total_seconds"]
for row in results
if row["experiment"] == "A-Baseline"
])
ranking = []
for name, _, _, _, _ in CONFIGS:
times = [
row["total_seconds"]
for row in results
if row["experiment"] == name
]
median = statistics.median(times)
speedup = baseline / median
improvement = (
(baseline - median) / baseline * 100
)
ranking.append(
(name, median, speedup, improvement)
)
ranking.sort(key=lambda row: row[1])
for name, median, speedup, improvement in ranking:
print(
f"{name:15s}",
f"{median:8.3f}s",
f"加速比={speedup:.2f}",
f"改善率={improvement:.2f}%"
)
print("CSV 輸出位置:", output_path)
clear_job_group(sc)
input("請觀察 Spark Web UI,按 Enter 結束...")
finally:
spark.stop()
9-2 執行效能測試
python -u exp05_benchmark.py
程式將執行六種設定, 每種設定重複三次, 共十八組測試。
每輪使用固定亂數種子重新安排測試順序, 並以總執行時間的中位數進行比較, 降低單次測試及固定順序所造成的影響。
最後自動輸出:
spark_benchmark_results.csv
十、使用 Pandas 與 Matplotlib 視覺化測試結果
Spark 負責大數據運算, 而 Pandas 負責整理少量的效能測試結果。 這也說明兩種工具可以互相搭配, 而不是彼此取代。
10-1 安裝套件
python -m pip install pandas matplotlib
10-2 建立 plot_benchmark.py
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
path = (
Path(__file__).resolve().parent
/ "spark_benchmark_results.csv"
)
df = pd.read_csv(path)
summary = df.groupby(
"experiment"
)["total_seconds"].median()
summary = summary.sort_values()
baseline = summary["A-Baseline"]
report = pd.DataFrame({
"Median Seconds": summary,
"Speedup": baseline / summary,
"Improvement (%)": (
(baseline - summary) / baseline * 100
)
})
print(report.round(3))
ax = summary.plot(
kind="barh",
figsize=(10, 5)
)
ax.set_title("Spark Optimization Benchmark")
ax.set_xlabel("Median Execution Time (seconds)")
ax.set_ylabel("Experiment")
for container in ax.containers:
ax.bar_label(container, fmt="%.3f")
ax.invert_yaxis()
plt.tight_layout()
plt.savefig(
path.parent / "spark_benchmark.png",
dpi=160
)
plt.show()
執行:
python plot_benchmark.py
【插入 spark_benchmark.png 實測圖表】
圖:六種 Spark 效能策略的執行時間比較。
十一、如何計算效能改善率?
11-1 Speedup 加速比
Speedup = 原始執行時間 / 改善後執行時間
例如原始執行時間為 10 秒,改善後為 4 秒:
Speedup = 10 / 4
= 2.5 倍
11-2 Improvement 效能改善率
改善率 = (原始時間 - 改善後時間)
/ 原始時間 × 100%
改善率 = (10 - 4) / 10 × 100%
= 60%
十二、Spark Web UI 效能診斷指南
| 觀察現象 | 可能原因 | 改善方向 |
|---|---|---|
| Tasks 太少 | Partition 數量不足 | 評估增加 Partition |
| 大量短時間 Tasks | 分割過細、排程成本高 | 減少 Partition 或啟用 AQE |
| Input 重複增加 | 重複掃描原始資料 | 評估 Cache / Persist |
| Shuffle Write 過大 | 大量資料重新分配 | 提早過濾、減少不必要欄位與交換 |
| 少數 Tasks 特別慢 | 可能存在資料傾斜 | 檢查 Partition 分布與 Join 策略 |
| GC Time 過高 | 可能存在記憶體壓力 | 檢查快取策略與記憶體配置 |
| Disk Spill 增加 | 部分運算資料溢寫至磁碟 | 檢查資料量、分割與運算記憶體 |
上述現象與原因並非一對一的必然關係, 應配合 Stage 詳細資訊與 Physical Plan 進行診斷。
十三、效能最佳化的工程思維
資訊工程師不應只依靠直覺調整系統參數, 而應該透過量測、分析、假設與實驗, 找出問題並驗證改善成果。
十四、學生實作學習單
| 任務 | 繳交成果 |
|---|---|
| 實驗一:Partition | 不同 Partition 設定的時間與 Tasks 比較 |
| 實驗二:Cache | Storage 截圖、快取前後時間比較 |
| 實驗三:Shuffle | Stages 截圖、Shuffle Read / Write 比較 |
| 實驗四:AQE | AQE 開啟與關閉的執行計畫比較 |
| 整合實驗 | 效能測試 CSV 與長條圖 |
| 學習心得 | 說明最佳設定及其選擇理由 |
思考與討論
- 為什麼 Partition 越多不一定越快?
- 為什麼 Cache 適合重複使用的資料?
- Cache 建立時間是否應納入效能比較?
- 為什麼 GroupBy 可能產生 Shuffle?
- 局部聚合如何減少資料交換量?
- AQE 如何減少不必要的 Tasks?
- 為什麼效能測試應重複執行?
- 為什麼最佳化後仍需驗證統計結果?
- 單機平行運算與多機分散式運算有何不同?
- 如何利用 Spark Web UI 找出效能瓶頸?
十五、延伸挑戰:從百萬筆到千萬筆
完成百萬筆資料測試後, 可以修改前一篇的資料產生程式, 進一步比較不同資料規模。
| 資料規模 | 學習重點 |
|---|---|
| 100,000 筆 | 觀察 Spark 固定運算成本 |
| 1,000,000 筆 | 平行運算與快取策略 |
| 5,000,000 筆 | 觀察記憶體與 Shuffle 成本 |
| 10,000,000 筆 | 觀察更大規模的效能變化 |
十六、結語:從大數據使用者走向大數據工程師
學會 PySpark 的 API, 只是進入大數據運算的第一步。 更重要的是理解系統如何安排資料與運算資源。
Partition 決定資料如何分割, Cache 決定資料如何重複使用, Shuffle 反映資料交換成本, AQE 則讓 Spark 能依據執行期間的資訊調整策略。
透過智慧養殖資料與 Spark Web UI, 學生不僅可以完成資料分析, 更能學習系統監控、效能診斷、 實驗設計及資訊工程的問題解決方法。
十七、參考資源
- Apache Spark 官方網站
- Spark SQL Performance Tuning
- Spark Monitoring and Instrumentation
- Spark Web UI
- PySpark API Reference
下一篇進階實驗
Python × PySpark × Django: 透過 Spark REST API 打造智慧養殖 大數據運算監控 Dashboard
下一步將整合 Spark REST API、 Python、Django 與網頁視覺化技術, 讓學生自行開發大數據系統監控平台。
沒有留言:
張貼留言