Advanced Python Teaching Lesson 1: Cython & PyPy

Lesson 1: Cython & PyPy – Achieving Maximum CPU Acceleration (180 min practical lesson plan, non-table version)

5 min Pre-class Check

  • Python 3.12 is installed with development headers

  • Execute the one-click script in the terminal curl -sSL

    https://raw.githubusercontent.com/yourrepo/setup.sh

    | bash Script content: install cython numpy pytest py-spy

Class Flow

0–10 min Warm-up Run a pure Python + Numpy loop live, recording a baseline of 1.3 s.

10–30 min Quick Explanation Explain Cython in three sentences: write .pyx → add types → convert to C extension. Then spend two minutes explaining the warm-up of PyPy tracing JIT and the limitations of the C-API. Remind about the three major pitfalls in benchmarking: I/O interference, cache jitter, and perf event overflow.

30–60 min Live Coding The instructor shares the screen to create sum_cython.pyx, adding typed memoryview line by line, disabling boundscheck and wraparound. Students follow along, saving automatically compiles the code.

60–90 min First Test Run pytest to ensure correct results, then in IPython use %timeit, obtaining 30 ms, an improvement of about 40×.

90–120 min Flame Graph Run in the terminal py-spy top -d 20 –native — python bench.py Students take screenshots, hotspots have moved into pure C loops, Python frames disappear.

120–150 min Extreme Optimization Add prange + OpenMP, running on an 8-core machine down to 8 ms, recording three sets of data: pure Python 1.3 s → Cython 30 ms → Cython+OpenMP 8 ms.

150–170 min PyPy Comparison Create a new pypy3 venv, the same script takes 1.8 s, conclusion: choose Cython for CPU-intensive scenarios, consider PyPy for I/O-intensive scenarios.

170–180 min Summary & Homework Three key points: type declarations, memoryview, compilation flags. Homework: choose a Numpy loop, achieve a speedup of ≥10× after cythonizing, and submit three flame graphs.

Post-class Homework

  1. Fork the template repository, include your .pyx and setup.py

  2. Use py-spy to generate three flame graphs: original, Cython, OpenMP

  3. Write a PR description detailing the time comparison, with a single pip command to reproduce

Leave a Comment