Introduction
Python easy aur readable language hai, lekin kabhi-kabhi ye slow lag sakti hai — especially jab hum large data ya heavy computation ke sath kaam karte hain. Yahaan hum seekhenge kaise apna Python code fast aur efficient banayein.
1️⃣ Code Optimization Basics
Sabse pehle apne code ka logic aur structure optimize karo. Unnecessary loops aur repeated calculations avoid karo.
# Slow way
squares = []
for i in range(1000000):
squares.append(i * i)
# Fast way (using list comprehension)
squares = [i * i for i in range(1000000)]
List comprehension internal C-level optimization use karta hai, isliye wo normal loop se fast hota hai.
2️⃣ Built-in Functions aur Libraries ka use karo
Python ke built-in functions jaise sum(), max(), aur min() C me optimized hote hain, isliye inhe manually loop likhne se better use karna chahiye.
nums = [1, 2, 3, 4, 5]
# Slow
total = 0
for n in nums:
total += n
# Fast
total = sum(nums)
3️⃣ Generators Use Karo Instead of Lists
Agar saara data ek sath memory me load karne ki zarurat nahi hai, to generators use karo.
# List comprehension
nums = [i * i for i in range(1000000)]
# Generator expression
nums = (i * i for i in range(1000000))
Generator ek time me ek value produce karta hai — memory bachaata hai aur bade datasets ke liye perfect hai.
4️⃣ Performance Measure karna (Profiling)
Performance improve karne se pehle ye jaan lo ki code me bottleneck kahan hai.
Iske liye timeit aur cProfile use hota hai.
import timeit
print(timeit.timeit("[i*i for i in range(1000)]", number=1000))
print(timeit.timeit("map(lambda x:x*x, range(1000))", number=1000))
timeit ek code snippet ko multiple baar run karke average time nikalta hai.
cProfile function-wise performance report deta hai.
5️⃣ NumPy ka Use
Numerical computations ke liye NumPy sabse fast library hai, kyunki ye C me likhi gayi hai.
import numpy as np
arr = np.arange(1000000)
squares = arr * arr
NumPy vectorized operations karta hai jisse loop likhne ki zarurat nahi padti, aur speed kai guna badh jaati hai.
6️⃣ Caching with functools.lru_cache
Agar koi function baar-baar same argument ke sath call hota hai, to result ko cache me store karna best practice hai.
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(35))
Caching se repeated calculation avoid hoti hai aur recursive code kaafi fast ban jaata hai.
7️⃣ Multiprocessing and Parallelism
Multi-core CPU me tasks ko parallel run karne ke liye multiprocessing use karte hain.
from multiprocessing import Pool
def square(n):
return n * n
if __name__ == "__main__":
with Pool() as p:
results = p.map(square, range(10))
print(results)
Pool multiple processes banata hai jisse kaam divide hota hai aur overall speed badhti hai.
8️⃣ Memory Optimization Tips
- Generators use karo list ke jagah.
- Classes me
__slots__use karo jab bohot saare objects bante hain. - Unused variables delete karo using
del. sys.getsizeof()se memory usage check karo.
import sys
x = [i for i in range(1000)]
print(sys.getsizeof(x))
Ye method dikhata hai ki koi object memory me kitni jagah le raha hai — optimization ke liye useful hai.