← Back to NumPy Course | Chapter 1: Getting Started | Lesson 7 of 7

NumPy vs Python speed

Timing the same job with a list loop and with NumPy shows how much faster whole-array maths is.

In this page:

  1. NumPy vs Python speed

NumPy vs Python speed

Vectorized NumPy code pushes loops into optimized C, avoiding per-element Python overhead. On large data the speed-up is commonly 10x to 100x. You can measure it yourself with the time module.

Note: Timing results vary by machine, so compare ratios rather than raw seconds.

Example: NumPy vs Python speed

python
import time
import numpy as np

n = 1_000_000
py_list = list(range(n))
arr = np.arange(n)

t0 = time.perf_counter()
py_sum = sum(x * 2 for x in py_list)
t_list = time.perf_counter() - t0

t0 = time.perf_counter()
np_sum = (arr * 2).sum()
t_np = time.perf_counter() - t0

print("Same answer:", py_sum == np_sum)
print("NumPy faster:", t_np < t_list)

# Output:
# Same answer: True
# NumPy faster: True
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Benchmarking tiny arrays where overhead dominates
  2. Timing the array creation instead of the operation
  3. Believing loops are always fine because they are simpler
Chapter Summary
  • Vectorization removes Python loop overhead
  • Speed-ups grow with data size
  • Measure with time.perf_counter
  • Avoid explicit loops on arrays
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.