Practice question · Multiple choice
A NumPy vectorised operation and an equivalent Python loop compute identical results, and the vectorised one can be fifty times faster. Where does the difference come from?
Hints
- Count how many times the Python interpreter is involved in each version.
- The arithmetic is identical. Ask what surrounds each operation.
Show the answer
B. From leaving the interpreter for compiled C over contiguous memory
Why
Same arithmetic, different overhead: a Python loop pays bytecode dispatch and type checks per element, while one NumPy call crosses into C once and runs a tight loop over contiguous memory with SIMD. It is why 'vectorise it' is the first optimisation in scientific Python, and why the advice does not transfer to C.
Practise Reproducibility and Good Practice
The app has 5 more questions on this lesson, and keeps your place in the course. Mathematics I is free to start.
More questions on Reproducibility and Good Practice
- A colleague sends a script and the number it printed. Select everything you still need before that result can…
- Vectorising usually gives a large speed-up, but sometimes almost none. Why does replacing a loop with an…
- Two runs of the same simulation with the same fixed seed and the same library versions should produce…
- Sort each practice by its effect on reproducibility.
- Complete the purpose of a test suite.
- A test suite contains 40 unit tests, of which 36 passed before a change. The change makes 3 previously…
- Order the steps of putting an analysis on a reproducible footing.