Skillversitas

Cell Magic Functions

Cell magics are functions applied to an entire cell, invoked by prefixing the first line with %%. Unlike line magics (single %), they can see and act on the whole cell body, which makes them ideal for timing, parallel execution, and output capture.

%%time - Time a Whole Cell

%%time
total = 0
for i in range(1000000):
    total += i
print(total)

IPython prints the wall-clock and CPU time for the entire cell, so you can compare algorithms without writing any timing code.

%%timeit - Looping Benchmark

%%timeit
sorted(range(1000))

%%timeit runs the cell many times (auto-calibrating the loop count) and reports the best or mean per-iteration time, which is far more reliable than a single run for microbenchmarks.

%%capture - Capture Output

%%capture result
print("captured stdout")
x = 41 + 1
print(x)

print(result.stdout)  # captured stdout
print(x)              # 42 - variables still execute

%%capture silences the cell's output but keeps executing it; result.stdout and result.stderr hold what was printed.

Other Common Cell Magics

  • %%python2 / %%python3 - run the cell under a different Python interpreter.
  • %%script myscript.py - treat the cell as a separate script file.
  • %%bash - run the cell body as shell commands.
  • %%writefile file.py - write the cell contents to a file (handy for saving helper code).
  • %%parallel / %%px - send the cell to IPython parallel engines (ipyparallel).

Summary

Cell magics (%%) act on the whole cell: %%time and %%timeit for benchmarking, %%capture to silence output while still executing, %%writefile and %%script for file and subprocess patterns, and language magics to switch interpreters. They replace whole blocks of boilerplate with a single first line.