2026年11月25日 星期三

Python × PySpark 大數據效能實戰: 從 Partition、Cache、Shuffle 到 AQE, 探索百萬筆智慧養殖資料的效能最佳化

Python × Big Data × Spark × 智慧養殖

Python × PySpark 大數據效能實戰: 從 Partition、Cache、Shuffle 到 AQE, 探索百萬筆智慧養殖資料的效能最佳化

大數據系統的效能,不只是取決於 CPU 的速度, 更取決於資料如何分割、如何重複使用、 如何交換,以及如何安排運算工作。

本篇延續百萬筆智慧養殖資料與 Spark Web UI 實驗, 透過四個動手作實驗, 讓學生從觀察大數據運算, 進一步學習如何改善大數據運算效能。

一、從上一個實驗發現問題

在前一篇 Spark Web UI 實驗中, 我們成功使用 PySpark 分析一百萬筆智慧養殖模擬資料。

1,000,000 智慧養殖資料筆數
7 原始 Partition 數量
16 本機運算 Cores
33 Completed Tasks
102.7 MiB 累計資料讀取量
61.4 KiB Shuffle Write
6.564 秒 資料處理時間
0 Failed Tasks

從這些數據可以發現, Spark 雖然已經成功完成所有分析工作, 但仍有許多值得探討的效能問題。

  1. 為什麼有 16 個邏輯運算資源, 原始資料卻只有 7 個 Partition?
  2. 為什麼約 25 MiB 的 CSV, 累計讀取量會超過 100 MiB?
  3. 為什麼各魚塭分組統計的 Shuffle 量較大?
  4. 為什麼設定 200 個 Shuffle Partitions, 實際執行的 Tasks 卻可能遠少於 200?
本篇將以這四個問題作為學習起點。 效能最佳化不是直接增加 CPU 或記憶體, 而是先觀察系統行為,再提出改善策略, 最後透過實驗數據驗證。

二、四大效能最佳化技術

Partition 資料分割
決定運算工作的粒度與平行程度。
Cache 資料快取
減少重複讀取與重複計算。
Shuffle 資料交換
觀察跨 Partition 的資料移動成本。
AQE 自適應查詢執行
依據執行期間的資訊調整運算計畫。
技術 主要問題 觀察頁面
Partition 資料如何分配? Stages
Cache 如何避免重複讀取? Storage、Executors
Shuffle 資料交換成本有多大? Stages、SQL
AQE 如何動態調整運算計畫? SQL / DataFrame

三、實驗環境與準備工作

沿用前一篇已經成功執行的環境。

項目環境
作業系統Windows 10
Python3.14
JavaJDK 17
Spark4.3.0(前次實測畫面)
Masterlocal[*]
Web UIlocalhost: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)
本篇保留前次 Windows 環境除錯後的程式設計方式, 不使用可能在部分 PySpark 版本中不存在的 clearJobGroup() 方法。

五、實驗一:Partition 資料分割與平行運算

5-1 什麼是 Partition?

Partition 是 Spark 將資料切分後的基本運算單位。 一個 Stage 通常會針對需要處理的每個 Partition 安排一個 Task。

1,000,000 筆智慧養殖資料
↓
P0 P1 P2 P3
↓
Task 0 Task 1 Task 2 Task 3
↓
彙整分析結果

Partition 太少,可能無法充分利用運算資源; Partition 太多,則可能增加 Task 排程與管理成本。

5-2 前次實測的 Partition 分布

Partition ID資料筆數
0161,739
1157,567
2157,556
3157,551
4157,563
5157,561
650,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待測待測待測
本實驗將 repartition() 所產生的資料交換成本 一併納入計時。 因此測量的是「重新分割加上統計分析」的整體成本, 並非單純比較不同 Partition 的運算速度。

5-7 思考問題

  1. Partition 數量越多,執行速度一定越快嗎?
  2. 16 個 Cores 是否一定要設定 16 個 Partition?
  3. 為什麼 repartition() 可能增加 Shuffle?
  4. 哪一種設定最適合目前的電腦與資料量?

六、實驗二:Cache 資料快取

6-1 為什麼需要 Cache?

前一次實驗中, 原始資料每次完整掃描約為 25.7 MiB, 但累計 Input 卻達到 102.7 MiB。

這是因為 Spark 採用 Lazy Evaluation(延遲求值)。 若沒有適當快取資料, 不同 Action 可能重新執行相同的資料讀取流程。

未使用 Cache
CSV 檔案
↓
讀取 → 整體統計
讀取 → 低溶氧分析
讀取 → 魚塭統計
讀取 → 水溫分析
使用 Cache
CSV 檔案
↓
快取資料
↓
整體統計
低溶氧分析
魚塭統計
水溫分析

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()。

DataFrame 的 cache() 在現代 PySpark 中, 預設通常採用 MEMORY_AND_DISK_DESER。 可以透過 df.storageLevel 查看實際設定。

6-7 實驗紀錄表

測試項目實測時間
未使用 Cache待測
建立 Cache待測
使用 Cache 分析待測
含建立成本的總時間待測
快取記憶體使用量待測
Cache 並不是免費的。 建立快取需要時間與記憶體。 如果資料只使用一次,快取不一定能改善效能。 另外,本實驗先執行未快取版本, 可能受到 JVM 暖機及作業系統檔案快取影響。 正式比較時應重複測試並交換測試順序。

七、實驗三:Shuffle 資料交換成本

7-1 什麼是 Shuffle?

當 Spark 必須將相同魚塭的資料重新集中, 或進行全域排序、分組統計與資料連接時, 就可能需要跨 Partition 交換資料。 這個過程稱為 Shuffle。

P0:魚塭 A、B P1:魚塭 B、C P2:魚塭 A、C
↓
Shuffle
依魚塭編號重新分配資料
↓
魚塭 A 魚塭 B 魚塭 C
↓
完成各魚塭水質統計

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 可能增加額外資料交換 待測
本實驗四項工作的輸出內容不同, 而且 A 使用 Python foreachPartition()。 因此主要比較 Shuffle 指標及執行計畫, 不宜直接以總執行時間判定哪一種操作較有效率。

7-5 Spark 為什麼先進行局部聚合?

假設三個 Partition 都有同一個魚塭的 DO 資料。

PartitionDO 資料局部總和筆數
P04、6、8183
P13、582
P26、8142

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 則可以在執行過程中取得實際統計資訊, 並據此調整後續的運算策略。

建立初始 Physical Plan
↓
執行部分運算階段
↓
取得 Runtime Statistics
↓
AQE 動態調整執行計畫
↓
執行調整後的運算工作

8-2 AQE 的三項重要能力

Coalesce 合併過小的 Shuffle Partitions, 減少不必要的 Tasks。
Join Strategy 依實際資料量調整部分 Join 策略。
Skew Join 在適用的 Join 情境中, 改善資料傾斜所造成的負載不均。

8-3 為什麼 200 個 Shuffle Partitions 可能變成一個?

在前次智慧養殖實驗中, 我們看到以下執行計畫:

Exchange

hashpartitioning(pond_id, 200)

AdaptiveSparkPlan

然而在 Stages 頁面中, 最終彙整階段可能只需要一個 Task。

初始設定:200 Shuffle Partitions
↓
實際 Shuffle 資料量很小
↓
AQE:合併過小的 Partitions
↓
較少的 Tasks

圖: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 Partitions200200
實際 Shuffle 後 Tasks待測待測
Shuffle Write待測待測
Shuffle Read待測待測
執行時間待測待測
是否出現 AdaptiveSparkPlan待測待測
AQE 並不保證所有查詢都會更快, 也不保證一定會將 200 個 Partition 合併為一個。 本實驗應以實際 Tasks 數量與執行計畫作為主要證據。

九、實驗五:整合效能最佳化測試

完成四個基礎實驗後, 接下來將不同效能策略整合成一個測試程式。

組別 Partition Cache Shuffle Partitions AQE
A 基準組原始否200否
B16否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 進行診斷。

十三、效能最佳化的工程思維

1. 觀察 Spark Web UI
↓
2. 發現效能問題
↓
3. 提出改善假設
↓
4. 調整 Partition、Cache、Shuffle、AQE
↓
5. 重複實驗與量測
↓
6. 驗證統計結果正確性
↓
7. 選擇適合的運算策略

資訊工程師不應只依靠直覺調整系統參數, 而應該透過量測、分析、假設與實驗, 找出問題並驗證改善成果。

十四、學生實作學習單

任務繳交成果
實驗一:Partition 不同 Partition 設定的時間與 Tasks 比較
實驗二:Cache Storage 截圖、快取前後時間比較
實驗三:Shuffle Stages 截圖、Shuffle Read / Write 比較
實驗四:AQE AQE 開啟與關閉的執行計畫比較
整合實驗 效能測試 CSV 與長條圖
學習心得 說明最佳設定及其選擇理由

思考與討論

  1. 為什麼 Partition 越多不一定越快?
  2. 為什麼 Cache 適合重複使用的資料?
  3. Cache 建立時間是否應納入效能比較?
  4. 為什麼 GroupBy 可能產生 Shuffle?
  5. 局部聚合如何減少資料交換量?
  6. AQE 如何減少不必要的 Tasks?
  7. 為什麼效能測試應重複執行?
  8. 為什麼最佳化後仍需驗證統計結果?
  9. 單機平行運算與多機分散式運算有何不同?
  10. 如何利用 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, 學生不僅可以完成資料分析, 更能學習系統監控、效能診斷、 實驗設計及資訊工程的問題解決方法。

真正的大數據效能最佳化, 不是讓電腦盲目增加運算工作, 而是讓電腦減少不必要的工作。

十七、參考資源

下一篇進階實驗

Python × PySpark × Django: 透過 Spark REST API 打造智慧養殖 大數據運算監控 Dashboard

下一步將整合 Spark REST API、 Python、Django 與網頁視覺化技術, 讓學生自行開發大數據系統監控平台。

沒有留言:

張貼留言