← Back to NumPy Course | Chapter 12: Advanced Topics | Lesson 6 of 7

Performance के Tips

कुछ habits, जैसे vectorizing और सही dtype चुनना, NumPy code को dramatically तेज़ बनाते हैं।

In this page:

  1. Performance Tips

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

python
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. #}
आम गलतियां
  1. Loops के अंदर arrays grow करना
  2. जब float32 काफी हो float64 इस्तेमाल करना
  3. बिना 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:

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.