การ optimize Python เริ่มต้นด้วยการ profile เพื่อหาคอขวด (bottleneck) ที่แท้จริง — ไม่ใช่การเดา ลักษณะของ Python ที่เป็นภาษา interpreted และไดนามิกทำให้มันช้ากว่าภาษาที่ compile ดังนั้นการ optimize จึงเน้นไปที่อัลกอริทึมที่ดีขึ้น การใช้ประโยชน์จากไลบรารีที่หนุนหลังด้วย C และการลด overhead ของ interpreter ใน hot path
profile ก่อน
import cProfile
cProfile.run("my_function()") # shows time spent per function call
# line-level profiling (third-party)
