Skip to content

perf(parlio): investigate why wave3 encode measures ~6µs/LED (LUT vs bit-swizzle vs gather vs logging) #2522

Closed

Description

@zackees

Summary

A debug-build hardware measurement put PARLIO show() "encode" at ~25 ms for 16×256 (4096 LEDs) ≈ 6 µs/LED. Expected for a LUT-based wave3 encoder hot in I-cache is ~1000 LEDs/µs ≈ 0.001 µs/LED — a ~6000× discrepancy. A -Og debug build is only ~3–5× slower than -O2, so optimization level alone cannot explain it. We need to find where the time actually goes, and specifically whether the bottleneck is the LUT lookup, the bit-transpose/swizzle, the outer populate loop / per-lane gather, logging, or something that isn't encode at all (e.g. the per-frame peripheral disable()/enable()).

Context: measured via measureParlio on ESP32-P4 (16×256). Build was build_type=debug, -Og, -DFASTLED_DEBUG=1, -DCORE_DEBUG_LEVEL=5, -DLOG_LOCAL_LEVEL=ESP_LOG_VERBOSE. Refs #2518, PR #2521.

What the code already does (narrows the suspects)

  • The wave3 inner functions (wave3_convert_byte_to_wave3byte, wave3Transpose_{2,4,8,16} in src/fl/channels/detail/wave3.hpp) are already FASTLED_FORCE_INLINE FL_IRAM FL_OPTIMIZE_FUNCTION, and FL_OPTIMIZE_FUNCTION = __attribute__((optimize("O3"))) on GCC. So the transpose/LUT are O3 + inlined + in IRAM even in a debug build — they should NOT be slow regardless of build type.
  • The caller ParlioEngine::populateDmaBuffer() (src/platforms/esp/32/drivers/parlio/parlio_engine.cpp.hpp, ~L795–1050) is not force-optimized. Its per-byte-position loop does, per output byte: a per-lane gather mScratchBuffer[lane*mLaneStride + startByte + byteOffset] (up to 16 reads), a stack temp, the transpose call, and a memcpy of the transposed bytes. At -Og this outer loop is unoptimized.
  • No FL_LOG_*/ESP_LOG* were found in the inner transpose loop, but logging elsewhere in show()/beginTransmission() at CORE_DEBUG_LEVEL=5 is not yet ruled out.

Hypotheses (ranked)

# Hypothesis Predicted signature
H1 Outer populateDmaBuffer loop + per-lane gather at -Og dominates (strided scratch reads, no vectorization, memcpy per position) Release build collapses encode; transpose micro-bench already fast
H2 The 25 ms is NOT encode — it's the per-frame disable()/enable() or other show() overhead/logging Sub-timers show encode small, other stage large
H3 Verbose logging somewhere in the show() path (CORE_DEBUG_LEVEL=5) LOG_NONE build collapses the time
H4 Bit-swizzle (transpose) genuinely expensive at 16 lanes Transpose micro-bench dominates even at O3
H5 LUT lookups (cache/latency) dominate LUT-only micro-bench ≈ full transpose time

Investigation plan

Phase 0 — clean re-measure (in progress): rebuild -O2, CORE_DEBUG_LEVEL=0, LOG_NONE, no FASTLED_DEBUG; rerun measureParlio 16×256. Decision: encode → ~1–3 ms ⇒ debug/logging artifact (H1/H3); still ~20 ms ⇒ genuine encoder cost (H4/H5).

Phase 1 — attribute the time: add micros() sub-timers in beginTransmission() around (a) the populate/encode loop, (b) disable()/enable(), (c) transmit() submit. Report each via measureParlio. (H2)

Phase 2 — separate LUT vs swizzle vs gather (the core question): add a host/device micro-benchmark RPC that runs, on a fixed buffer, N iterations of:

  1. gather only — read the strided scratch bytes, no transpose.
  2. LUT only — wave3_convert_byte_to_wave3byte per lane, no swizzle write-out.
  3. full transpose — wave3Transpose_16 (LUT + swizzle).
  4. memcpy only — the output copy.
    Report ns/byte for each. full − LUT = swizzle cost; LUT − 0 = LUT cost; gather/memcpy isolate the caller overhead. This directly answers "is the LUT or the bit-swizzle the bottleneck."

Phase 3 — fix the hot path: based on Phase 2, apply FL_OPTIMIZE_FUNCTION/FASTLED_FORCE_INLINE to populateDmaBuffer (or restructure the gather to be sequential/SIMD-friendly), strip any hot-path logging, and re-measure.

Phase 4 — only if encode ≪ wire: ISR stream-encode (encode chunk N+1 in the txDone ISR during chunk N's transmit). Blocked by (a) the mandatory per-frame disable()/enable() serialization and (b) the ~20µs inter-chunk seam — both must be solved (see #2518).

Phase 5 — validate: release build, FPS up, RX-loopback mismatchedLeds==0 (needs GPIO5→6 jumper).

Deliverable

A definitive ns/byte breakdown (gather / LUT / swizzle / memcpy / logging / peripheral-reset) and a concrete fix that gets encode to its expected ~1000 LEDs/µs, enabling the ISR-streaming overlap design.

Activity

  1. zackees commented on May 28, 2026

    @zackees
    MemberAuthor

    Phase 0 result — NOT a debug/logging artifact; likely memory-bandwidth (PSRAM) bound

    Rebuilt release (-O2, CORE_DEBUG_LEVEL=0, LOG_LOCAL_LEVEL=ESP_LOG_NONE, no FASTLED_DEBUG) and re-ran measureParlio 16×256 on ESP32-P4:

    Build show_us (encode) wire pipelined/frame
    Debug (-Og, verbose log) 25,449 ~6.3 ms 31,772
    Release (-O2, no log) 20,971 ~6.3 ms 27,287

    Only ~16% faster — decisively not a logging/opt artifact. Real cost ≈ 5 µs/LED (≈5000× over the ~1000 LEDs/µs target).

    This rules H4/H5 (LUT/swizzle compute) DOWN and promotes a new lead

    • The wave3 inner functions are already __attribute__((optimize("O3"))) + always_inline + FL_IRAM, so -O2 cannot speed them and they are almost certainly not the bottleneck.
    • The encode writes its ~37 KB transposed output into the PSRAM DMA ring (alloc_psram_bytes≈340 KB confirms PSRAM, internal SRAM delta only ~11 KB). Non-cacheable PSRAM scattered byte/word writes are bandwidth-bound and -O2-immune — this fits the 16% observation perfectly.
    • Pipelined still == serialized (27.3 ms) ⇒ still no overlap (per-frame disable()/enable() serialization, tracked in perf(parlio): umbrella for ESP32-P4 PARLIO output and show timing work #2518).

    New top hypothesis (H6): output write to non-cacheable PSRAM dominates

    ~36,864 output bytes per frame written into non-cacheable DMA PSRAM; at hundreds of ns per uncached write this alone is ~15–20 ms. Compute (LUT+swizzle, in IRAM/O3) is likely a small fraction.

    Revised next steps

    1. Sub-timer (Phase 1): split beginTransmission into encode-loop vs disable()/enable() vs submit. Confirm the ~21 ms lives in the encode/populate loop (not the peripheral reset).
    2. PSRAM vs SRAM A/B (new, decisive for H6): encode into a fast internal-SRAM scratch then bulk-copy to the DMA buffer — OR allocate the DMA ring in internal SRAM (16×256 ring ≈111 KB fits the 512 KB cap). If show collapses ⇒ confirmed memory-bound, and that IS the fix.
    3. Micro-bench (Phase 2): still separate gather / LUT / swizzle / memcpy, but now also destination = SRAM vs PSRAM to isolate the write-bandwidth term.

    If H6 holds, the fix is "encode to SRAM, DMA from SRAM (or DMA-copy to PSRAM)", not touching the LUT/transpose at all — and once encode is fast, the ISR-streaming overlap (#2518) becomes worthwhile.

  2. zackees commented on May 28, 2026

    @zackees
    MemberAuthor

    Phase 1 attribution — the ~21ms splits cleanly (sub-timers in beginTransmission)

    measureParlio 16×256, release build, baseline (PSRAM DMA, with per-frame reset), with new begin_us/encode_us/reconfig_us timers:

    Piece Time
    reconfig_us (per-frame disable()+enable()) 32 µs
    encode_us (populate/encode loop) 14,583 µs
    begin_us (whole beginTransmission) 14,780 µs
    show − begin (FastLED.show()/channel-manager layer) ~6,210 µs
    show_avg 20,990 µs

    Conclusions

    • The per-frame disable()/enable() reset is NOT the cost (32 µs). This kills the earlier "peripheral-reset serializes frames" hypothesis from perf(parlio): umbrella for ESP32-P4 PARLIO output and show timing work #2518 — confirmed independently by the earlier no-reset A/B (show unchanged at 19ms).
    • The encode loop is the cost: 14.6 ms for 4096 LEDs ≈ 3.6 µs/LED (~3600× over the ~1000 LEDs/µs target).
    • The wave3 LUT+transpose are already __attribute__((optimize("O3"))) + always_inline + FL_IRAM, so the slowness is in what wraps them inside populateDmaBuffer:
      • the per-byte-position outer loop (not force-optimized), and
      • the strided source gather mScratchBuffer[lane*mLaneStride + startByte + byteOffset] — 16 scattered reads per byte-position. ≈19 µs/position is far too slow for compute; this smells like uncached/strided reads from a PSRAM source buffer (new hypothesis H7).
    • Separately, ~6 ms lives above the engine in FastLED.show()/the channel manager (16 channels) — its own follow-up.

    Next (Phase 2 micro-benchmark, now well-targeted)

    Add an RPC that, on a fixed frame, times in isolation: (1) source gather only, (2) LUT only, (3) full wave3Transpose_16, (4) memcpy only — each with the source in SRAM vs PSRAM. That pins the 14.6 ms to gather-bandwidth vs swizzle-compute and tells us whether the fix is "stage the source in SRAM" vs "optimize the transpose/outer loop." Also profile the ~6 ms show()/manager overhead.

    Instrumentation lives on branch feat/parlio-pingpong-overlap (debug timers + parlioDebugTimings() accessor + measureParlio fields).

  3. zackees commented on May 28, 2026

    @zackees
    MemberAuthor

    Experiment series to pinpoint the PARLIO encode slowness

    Established so far (16×256, ESP32-P4, release -O2, no logging): show() = 21 ms = encode ≈14.6 ms + ≈6 ms above the engine (FastLED.show()/channel-manager) + reconfig 0.03 ms (negligible). LUT/transpose are already O3+inline+IRAM. Moving the DMA output to SRAM saved only ~2 ms ⇒ the cost is read/loop side, not output writes. Leading hypothesis: the source/scratch buffer is in PSRAM and the 16-lane strided gather pays scattered-PSRAM latency.

    Each experiment lists hypothesis → method → decision. E1–E2 pin the root cause; E3–E6 preview fixes; E7 chases the separate 6 ms; E8–E9 finalize/validate.

    # Experiment Method Confirms / decides
    E1 Where does the source buffer live? At beginTransmission, report esp_ptr_external_ram(mScratchBuffer) + the addr range; same for the DMA buffer. RPC field. Is the source in PSRAM (scatter-read penalty) — the core suspect
    E2 Stage-isolated micro-bench (the key one) New benchEncode RPC: on a fixed frame, time N iters of each stage separately — (1) gather-only, (2) +LUT (wave3_convert_byte_to_wave3byte/lane), (3) +swizzle (wave3Transpose_16 → stack temp), (4) write-only (bulk store 48B/pos), (5) full. Parameterize src∈{SRAM,PSRAM} × dst∈{SRAM,PSRAM}. Report ns/byte. Splits 14.6 ms into gather / LUT / swizzle / write, and the SRAM-vs-PSRAM penalty per direction. swizzle = full−LUT, LUT = (2)−(1), etc.
    E3 Source-in-SRAM A/B Copy source to an internal-SRAM staging buffer first; re-run measureParlio; compare encode_us. If encode collapses ⇒ read-side PSRAM scatter is dominant ⇒ fix = SRAM source
    E4 SRAM scratch + bulk copy (your proposal) Encode into SRAM scratch, then ONE sequential memcpy to the PSRAM DMA buffer; measure encode_us + copy time. Quantifies the write-side win of bulk vs scattered PSRAM writes
    E5 Cacheable PSRAM + esp_cache_msync Allocate DMA buffer cacheable (drop the non-cacheable MALLOC_CAP_DMA path) + writeback once before TX; measure. Cheaper alternative to SRAM staging if write-back cache hides PSRAM write latency
    E6 Force-optimize the outer loop Add FL_OPTIMIZE_FUNCTION to populateDmaBuffer (inner transpose already O3); measure with src/dst held in SRAM (isolate compute from memory). Isolates compiler-opt of the gather/loop from memory-bandwidth effects
    E7 Attribute the ~6 ms above the engine Timer around the channel-manager's pre-engine work (assembling 16 lanes into mScratchBuffer). If that scratch is PSRAM, the manager's scattered write of it likely IS the 6 ms — and the same buffer the engine then scatter-reads. Whether the source-buffer location hurts BOTH the 6 ms (manager write) and the 14.6 ms (engine read) — one fix for both
    E8 Async GDMA bulk copy If E4 wins, use ESP32-P4 async_memcpy (GDMA) for SRAM→PSRAM so the copy overlaps the next encode. Whether the bulk copy can be hidden, enabling the ISR-streaming overlap (#2518)
    E9 End-to-end + correctness Apply winning fix; re-measure encode_us + pipelined_per_frame_us; validate WS2812 output via RX-loopback mismatchedLeds==0 (needs GPIO5→6 jumper). Confirms the fix is real and signal-correct

    Expected outcome / done definition

    A ns/byte breakdown (gather / LUT / swizzle / write × SRAM/PSRAM) that names the dominant term, the location of both the source and DMA buffers, an explanation for the ~6 ms manager cost, and a validated fix bringing encode_us toward the ~1000 LEDs/µs target so ISR stream-encoding (#2518) becomes worthwhile.

    Instrumentation already on branch feat/parlio-pingpong-overlap (sub-timers, parlioDebugTimings, pipelined_per_frame_us, release/no-log P4 build). E1/E2 build on the same measureParlio/RPC harness.

  4. zackees commented on May 28, 2026

    @zackees
    MemberAuthor

    Smoking gun found: encode is Wave8-bound, not PSRAM-bound

    Ran the benchMem micro-benchmark (E1/E2) + a parlioDebugConfig accessor on the ESP32-P4 (16 lanes × 256 LEDs, PlatformIO -O2, no logging). Results overturn the PSRAM hypothesis.

    1. PSRAM is NOT the bottleneck (hypothesis refuted)

    benchMem allocates source+dest buffers in both SRAM and PSRAM and times the encode building blocks:

    Operation SRAM PSRAM Penalty
    strided 16-lane gather 205 µs 205 µs ×1.00
    full wave3 transpose (gather+transpose+memcpy) 3638 µs (→SRAM) 3638 µs (→PSRAM) ×1.00
    bulk memcpy → PSRAM (36864 B) — 76 µs (485 B/µs) —

    The ESP32-P4 L2 cache fully hides PSRAM latency for this access pattern. The proposed "SRAM scratch + bulk copy to PSRAM" comes out at ×0.98 (slightly worse, due to the extra copy). Do not pursue the SRAM-scratch path.

    2. The real cost: the driver uses Wave8, not Wave3

    parlioDebugConfig reports the runtime config of the real show():

    use_wave3 = 0      data_width = 16      ring_capacity = 98880 bytes
    encode_us = 14567  begin_us = 14777     reconfig_us = 33 (negligible)
    alloc_psram_bytes = 340312   (3 ring buffers of 98880 + padding)
    

    vs the isolated wave3 transpose of the identical 16×256 frame: 3641 µs.

    Wave3 (benchMem) Wave8 (real driver) Ratio
    DMA bytes / frame 36864 98880 2.68× (=8/3)
    encode time 3641 µs 14567 µs 4.0×
    ns / byte 98.8 147 1.49×

    So Wave8 costs 2.68× more bytes and its transpose is 1.49× less efficient per byte → 4.0× total. Memory (alloc_psram) is also ~2.68× bigger than it needs to be.

    3. Why Wave8 and not Wave3 — and it's correct

    mUseWave3 = canUseWave3(timing). For WS2812B_V5 (T1=225, T2=355, T3=645 ns, period 1225):

    T0H/period = 225/1225 = 0.184  → ×3 = 0.55 → round = 1 tick
    T1H/period = 580/1225 = 0.474  → ×3 = 1.42 → round = 1 tick
    ticks_bit0 (1) == ticks_bit1 (1)  → canUseWave3() = false → Wave8 fallback
    

    3-tick resolution genuinely cannot separate this timing's T0H from T1H, so the fallback is not a bug. But Wave8 (8 ticks/bit) is the maximum — the driver jumps straight to it. At 4 ticks the two levels separate cleanly:

    N ticks T0H ticks T1H ticks usable? rel. cost vs Wave8
    3 (Wave3) 1 1 ❌ same 0.375×
    4 (Wave4) 1 2 ✅ 0.5×
    5 1 2 ✅ 0.625×
    6 1 3 ✅ 0.75×
    8 (Wave8, current) 1 4 ✅ 1.0×

    Conclusion / next step

    The encode is bound by ticks-per-bit (output volume), not memory. The win is to encode at the minimum tick count that represents the timing (Wave4 for V5) instead of defaulting to Wave8 — cutting encode time and DMA RAM ~2×, validated by RX loopback for signal integrity. Filing a dedicated fix issue.

  5. zackees commented on May 31, 2026

    @zackees
    MemberAuthor

    Closing as research complete. Wave3 ns/byte breakdown captured; resulting encode optimizations shipped via #2553/#2555/#2557/#2559.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions