Skip to content

Test and measure PySpark workloads

This guide uses the PySpark 3.5.8 API and the site's local example tuple: CPython 3.11.18, Spark/PySpark 3.5.8, and Temurin Java 17.0.21.1+2. It is a documentation example, not a support promise for every PySparky repository. Check each project's README and CI for its tested versions.

Test behavior at the right boundary

Use ordinary Python unit tests for deterministic logic that does not need a Spark session. A mock can check that a function passes a table name or column to Spark, but it cannot prove Spark accepts or executes the expression.

Use a local Spark integration test for behavior that depends on Spark's analyzer, SQL null rules, data types, ordering, or execution. Build a small DataFrame from synthetic rows and an explicit schema. Assert the output schema and values, sort by stable keys before comparing rows, and keep collect() bounded. Use a deterministic session fixture and stop the session after the test suite. The testing example repository shows both test styles and links to the maintained how-to-test-your-spark source.

Keep actions visible. select, filter, join, and groupBy build a plan; collect, show, count, and writes can execute work. Put the action in the test or application boundary so a transformation's contract stays clear. Do not use a timing threshold in a normal unit test: JVM startup, scheduling, host load, and Spark version can change wall-clock time without changing correctness.

Inspect the query plan

DataFrame.explain prints a logical or physical plan for debugging. In Spark 3.5.8, common modes are:

Mode What it prints
simple The physical plan.
extended Parsed, analyzed, optimized, and physical plans.
formatted A physical-plan outline and details for each node.
cost A logical plan and available statistics.
codegen A physical plan and generated code when available.

Start with formatted when you need to connect operators to their details. Look for scans, filters, joins, sorts, Exchange nodes, and Python execution boundaries. The Spark Web UI adds runtime information such as stage durations, task distribution, shuffle read/write, and spill. The SQL performance guide describes Adaptive Query Execution (AQE), which can use runtime statistics to change a plan during execution.

An explain output is a plan, not a benchmark or a record of completed work. Statistics may be unavailable, and plans can change with input metadata, configuration, Spark version, and runtime statistics. Avoid snapshot-testing the entire plan string: assert the result contract, then inspect the plan when diagnosing a regression.

This bounded example prints a formatted plan and collects only three grouped rows. The marker makes it run in the documentation checks; the test does not assert a fixed plan string.

from pyspark.sql import SparkSession, functions as F, types as T

spark = (
    SparkSession.builder.master("local[1]")
    .appName("pysparky-explain-plan")
    .config("spark.ui.enabled", "false")
    .config("spark.sql.shuffle.partitions", "2")
    .getOrCreate()
)
try:
    schema = T.StructType(
        [T.StructField("id", T.LongType(), nullable=False)]
    )
    rows = [(value,) for value in range(12)]
    source = spark.createDataFrame(rows, schema).select(
        (F.col("id") % F.lit(3)).alias("bucket")
    )
    grouped = source.groupBy("bucket").count()
    grouped.explain(mode="formatted")

    rows = grouped.orderBy("bucket").collect()  # bounded action: three rows
    assert [(row["bucket"], row["count"]) for row in rows] == [
        (0, 4),
        (1, 4),
        (2, 4),
    ]
finally:
    spark.stop()

Measure an explicit action

Before timing, define what is equivalent: input rows and types, null policy, output semantics, Spark configuration, and the action that consumes the result. Inspect the plans, check outputs, and then measure the same action on each candidate. Separate Python time spent creating DataFrame transformations from time spent calling an action when that distinction matters. Be clear about what the timer includes: Spark planning and driver work can happen during an action call, in addition to executor work.

For a useful comparison:

  1. Use a representative scale and data distribution, or synthetic data shaped to exercise the same behavior. Tiny local examples validate mechanics, not cluster performance.
  2. Keep the action, input, partitioning, runtime versions, and relevant SQL settings the same. Record them with the result.
  3. Run a warm-up and several measured trials. Report the individual samples or a summary such as the median and range; do not turn one run into a universal speed claim.
  4. Inspect runtime metrics in the Spark UI to locate the work. The monitoring guide and Web UI reference explain job, stage, task, SQL, shuffle, and spill metrics.
  5. Treat cache state as part of the workload. DataFrame.cache() persists a frame using Spark's default storage level; cache only when the real job reuses that frame, measure the intended cold or warm behavior, and release it with unpersist() when finished. See the PySpark cache API.

The next example demonstrates timing mechanics for two equivalent native expressions over the same synthetic input. It warms each candidate, alternates which candidate runs first, verifies their bounded outputs, and times only a count() call. DataFrame objects and explain() output are prepared before the timer; the call can still include Spark planning, driver, and execution work. It prints local measurements without setting a threshold or claiming that either expression is faster. In a real comparison, replace the expressions with the alternatives you need to evaluate and run against data that represents your workload.

from statistics import median
from time import perf_counter

from pyspark.sql import SparkSession, functions as F

spark = (
    SparkSession.builder.master("local[1]")
    .appName("pysparky-benchmark-method")
    .config("spark.ui.enabled", "false")
    .config("spark.sql.shuffle.partitions", "2")
    .getOrCreate()
)
try:
    source = spark.range(10_000, numPartitions=2)
    queries = {
        "column expression": source.select(
            (F.col("id") % F.lit(100)).alias("bucket")
        ).groupBy("bucket").count(),
        "SQL expression": source.selectExpr("id % 100 AS bucket")
        .groupBy("bucket")
        .count(),
    }

    reference = [
        tuple(row)
        for row in queries["column expression"]
        .orderBy("bucket")
        .collect()
    ]
    alternative = [
        tuple(row)
        for row in queries["SQL expression"].orderBy("bucket").collect()
    ]
    assert reference == alternative

    for query in queries.values():
        query.explain(mode="formatted")

    samples = {name: [] for name in queries}
    names = list(queries)
    for trial in range(4):  # first pass warms up; next three are measured
        order = names if trial % 2 == 0 else list(reversed(names))
        for name in order:
            started = perf_counter()
            row_count = queries[name].count()  # explicit Spark action
            elapsed = perf_counter() - started
            assert row_count == 100
            if trial > 0:
                samples[name].append(elapsed)

    for name, timings in samples.items():
        print(f"{name}: median warmed count = {median(timings):.3f} s")
finally:
    spark.stop()

This small local run is not evidence of a speedup. The clock includes host load, JVM scheduling, and local execution, and the optimizer may produce the same plan for both expressions. Do not use the printed values as a CI acceptance threshold or as a claim about a distributed cluster.

References