Module 19 of 21 · Advanced Python for AI Development · Intermediate

Performance Optimization Techniques

Duration: 8 min

Optimize your AI code for speed and memory efficiency in production environments.

Profiling Code Performance

Use profiling tools to identify bottlenecks before optimizing.

import cProfile
import pstats

def slow_function():
    total = 0
    for i in range(1000000):
        total += i
    return total

# Profile the function
profiler = cProfile.Profile()
profiler.enable()
result = slow_function()
profiler.disable()

stats = pstats.Stats(profiler)
stats.sort_stats('cumulative')
stats.print_stats(5)

Try it in Google Colab: Open in Colab

Vectorization with NumPy

Replace loops with NumPy operations for 100x speedups.

import numpy as np
import time

# Slow: Python loop
data = list(range(1000000))
start = time.time()
result = [x * 2 for x in data]
print(f"Loop time: {time.time() - start:.4f}s")

# Fast: NumPy vectorization
data_np = np.arange(1000000)
start = time.time()
result_np = data_np * 2
print(f"NumPy time: {time.time() - start:.4f}s")
Loop time: 0.0523s
NumPy time: 0.0008s

💡 Tip: Always profile before optimizing. Focus on the slowest parts first for maximum impact.

❓ What's the first step in optimization?

← Previous Continue interactively → Next →

Related Courses