Performance के Tips
कुछ habits, जैसे vectorizing और सही dtype चुनना, NumPy code को dramatically तेज़ बनाते हैं।
In this page:
Performance Tips
Python loops की जगह vectorized operations इस्तेमाल करें और सबसे छोटा suitable dtype चुनें। Arrays grow करने की बजाय preallocate करें, needless copies avoid करें, और जहाँ safe हो += जैसे in-place operators इस्तेमाल करें। Optimize करने से पहले timeit से measure करें।
Note:
np.append से एक loop में append करना हर बार पूरा array copy करता है।
उदाहरण: Performance tips
import numpy as np
n = 5
out = np.empty(n)
for i in range(n):
out[i] = i ** 2
vec = np.arange(n) ** 2
print(out)
print(vec)
print(np.array_equal(out, vec))
a = np.ones(1000, dtype=np.float32)
print(a.nbytes, "bytes")
# Output:
# [ 0. 1. 4. 9. 16.]
# [ 0 1 4 9 16]
# True
# 4000 bytes
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. #}
आम गलतियां
- Loops के अंदर arrays grow करना
- जब float32 काफी हो float64 इस्तेमाल करना
- बिना measuring के optimize करना
चैप्टर सारांश
- Looping की बजाय Vectorize करें
- Arrays preallocate करें
- Compact dtypes चुनें
- पहले measure करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: