DEV Community

Cover image for Why Numpy is faster than Pure Python: A Speed Comparison
UWINTWALI Jean de Dieu
UWINTWALI Jean de Dieu

Posted on

Why Numpy is faster than Pure Python: A Speed Comparison

Have you ever wondered why data scientists and numerical computing enthusiasts swear by Numpy?

Today, I ran a simple experiment to compare the speed of Numpy versus Pure Python for vectorized operations and the results were mind-blowing!

The Experiment: Numpy vs. Pure Python

I wrote two functions performing the same task, adding two arrays element-wise, one using Pure Python and the other leveraging Numpy.

Here's the code:

import numpy as np
import time 

size_of_vec = 10000

def python_version():
    time_1 = time.time()
    x = range(size_of_vec)
    y = range(size_of_vec)
    z = [x[i] + y[i] for i in range(len(x))]
    return time.time() - time_1

def numpy_version():
    time_1 = time.time()
    x = np.arange(size_of_vec)
    y = np.arange(size_of_vec)
    z = x + y
    return time.time() - time_1

a = numpy_version()  # Numpy time
b = python_version() # Pure Python time

c = b / a
c = int(c)

print(f"Numpy Version: {a}")
print(f"Pure Python Version: {b}")
print(f"Numpy is {c} times faster than Pure Python!")
Enter fullscreen mode Exit fullscreen mode

The Results? Numpy Dominates!

Running this code, I found that Numpy was significantly faster, sometimes 100x or more than Pure Python, especially as the array size grows.

  • Numpy Version: Completed in microseconds.
  • Pure Python Version: Slower due to Python’s dynamic typing and loop overhead.

Why is Numpy So Much Faster?

  • Vectorized Operations: Numpy performs operations in optimized C/Fortran under the hood, avoiding Python’s slow loops.
  • Memory Efficiency: Numpy arrays are contiguous blocks in memory, while Python lists are flexible but slower.
  • No Type Checking: Numpy enforces fixed data types, reducing overhead.

Key Takeaway

For small arrays, the difference might seem negligible.

But as data scales, Numpy’s speed advantage becomes undeniable.

If you're working with numerical data, Numpy isn’t just an option, it’s a necessity for performance!


Next time you crunch numbers, let Numpy do the heavy lifting! 💪

Top comments (0)