IPython provides a set of convenient commands called “Magic Functions” for measuring code execution time or manipulating external files. These are executed by prefixing them with %.
List of Main Magic Commands
| Magic Function | Role | Parameter Example |
| %timeit | Measures execution time of code (calculates average over multiple runs). | %timeit range(100) |
| %run | Executes an external Python script file. | %run script.py |
| %history | Displays input history so far. | %history -n 1-5 |
| %save | Saves history of specified lines to a file. | %save file.py 1-10 |
| %load | Loads code from an external file into the current input cell. | %load script.py |
| %pwd | Displays the current working directory (path). | %pwd |
| %ls | Displays a list of files in the current directory. | %ls |
Execution Examples
1. Measuring Code Execution Time (%timeit)
Automatically loops the specified code multiple times to calculate the most accurate average execution time.
In [1]: %timeit list(range(1000))
9.85 µs ± 120 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
2. Executing External Scripts (%run)
Executes a .py file located in the current directory within the IPython environment. Variables after execution remain accessible within IPython.
sample.py (File created in advance)
print("This is a sample script.")
message = "Hello from script!"
Execution in IPython
In [2]: %run sample.py
This is a sample script.
In [3]: print(message)
Hello from script!
3. Referencing and Saving History (%history, %save)
You can check code entered in the past or select specific lines to save to a file.
# Execute some code
In [4]: s = "sample string"
In [5]: print(s)
sample string
# Check history (Display all without options)
In [6]: %history
%timeit list(range(1000))
%run sample.py
print(message)
s = "sample string"
print(s)
# Save specific lines (lines 4 and 5) to 'sample2.py'
In [7]: %save sample2.py 4 5
The following commands were written to file 'sample2.py':
s = "sample string"
print(s)
4. Loading Code (%load)
Expands the content of a file into the current cell. This is convenient when you want to check or edit the content before execution.
In [8]: %load sample2.py
# When executed, the cell content changes as follows:
# %load sample2.py
s = "sample string"
print(s)
Supplement: Line Magic and Cell Magic
- Line Magic (
%): Commands effective for a single line. (Example:%timeit) - Cell Magic (
%%): Commands effective for the entire cell. (Example: Writing%%timeitmeasures the time for the entire multi-line code in that cell.)
