5.4.5 · HinglishScientific Computing (Python)

Vectorization — avoiding Python loops, speed comparison

1,685 words8 min readRead in English

5.4.5 · Coding › Scientific Computing (Python)


WHY matter karta hai ye?

WHY slow hota hai Python loop? Python loop ki har iteration mein ye sab karna padta hai:

  1. Agla object fetch karo (ek boxed PyObject, raw number nahi).
  2. Runtime pe uska type check karo (Python dynamically typed hai).
  3. Sahi __add__/__mul__ method ko dispatch karo.
  4. Result ke liye ek naya Python object allocate karo.

Sirf do numbers add karne ke liye dozens of machine instructions lagte hain. Ek NumPy array raw float64 values ko memory mein tightly packed store karta hai, to C loop bas result[i] = a[i] + b[i] karta hai — ek CPU instruction, koi boxing nahi, koi type checks nahi.


WHAT hai speed model? (Scratch se derivation)

Chalo "100×" memorize karne ki jagah expected speedup derive karte hain.

elements pe ek operation ka total time:

  • Ek Python loop ke liye: bada hota hai (boxing, type check, dispatch). Ise ns kaho.
  • Ek vectorized op ke liye: bas ek raw CPU op hai. Ise ns kaho. Ek fixed C-call setup hota hai.
Figure — Vectorization — avoiding Python loops, speed comparison

HOW karte hain vectorize? (Patterns)


Common mistakes (Steel-manned)


Forecast-then-Verify


Recall Feynman: 12-saal ke bacche ko explain karo

Imagine karo tumhe 1,000,000 envelopes stamp karne hain. Tarika 1 (Python loop): har envelope ke liye tum almari pe jaao, stamp uthao, instructions padho, stamp lagao, stamp wapas rakho, ek note likho. Ek million baar repeat karo — bahut thaka dene wala! Tarika 2 (vectorization): tum ek fast robot ko kaho "in sabko ek hi tarah se stamp kar do," aur wo poori pile ek smooth motion mein karta hai bina har baar instructions re-read kiye. Same result, lekin robot boring setup pe ek million baar time waste nahi karta. Isliye vectorized code itna faster hota hai — ye repetitive thinking ek baar karta hai, har item ke liye ek baar nahi.


Flashcards

Python for loop numbers pe NumPy se slow kyun hota hai?
Har iteration objects box karta hai, runtime type-checking karta hai, method dispatch karta hai, aur new-object allocation karta hai — har element ke liye ek CPU op ki jagah dozens of instructions.
"Vectorization" ka matlab kya hai?
Ek operation ko poore array pe ek saath express karna taaki looping compiled C mein run ho, Python interpreter mein nahi.
Array op ke liye time model do.
; speedup large ke liye.
Bahut chhote arrays ke liye, kya vectorization hamesha faster hai?
Nahi — fixed C-call setup dominate karta hai, to scalar/loop faster ho sakta hai.
Loop mein np.append kyun bura hai?
Ye har call pe poora array copy karta hai → . List banao phir np.array, ya np.empty pre-allocate karo.
Kya np.vectorize(f) f ko fast banata hai?
Nahi — ye essentially ek Python-level loop hai; real speed ke liye NumPy ufuncs ya numba use karo.
Per-element if (jaise ReLU) ko vectorize kaise karte hain?
Boolean mask use karo: a[a<0]=0 ya np.where(a<0,0,a).
Broadcasting kis kaam aati hai?
Different shapes ke arrays combine karne ke liye (jaise row[:,None]+col[None,:]) nested Python loops se bachne ke liye.
for x in np_array iterate karna list se slower kyun ho sakta hai?
Har element ek np.float64 object mein unbox hota hai, normal Python loop se zyada overhead add karta hai.
Large N pe vectorized speed ko kya limit karta hai?
Memory bandwidth — CPU arithmetic ka wait nahi karta, data ka wait karta hai.

Connections

  • NumPy Arrays vs Python Lists — contiguous typed memory isliye vectorization kaam karta hai.
  • Broadcasting Rules — multi-dimensional combinations vectorize karna.
  • Universal Functions (ufuncs) — compiled C kernels jo aap call karte ho.
  • Big-O Complexity — isliye np.append-in-loop hai.
  • Numba and Cython — jab vectorization bhi kaafi nahi hota.
  • Memory Layout and Cache — vectorized ops pe bandwidth limits.

Concept Map

incurs

from

pushes loop into

operates on

avoids

replaces

gives

large N

tiny N setup dominates

large tau_py in

Python for loop

Per-element overhead

Boxing type check dispatch

Vectorization

Compiled C loop

Raw float64 packed memory

Time model T = setup + N x tau

Speedup ratio

Limit = tau_py / tau_vec ~ 100x

Small N vectorization slower