วันอังคารที่ 22 มีนาคม พ.ศ. 2554

[Python] Identify the bottlenecks by Python profilers

Python Profiler package เป็น package ไว้สำหรับ วิเคราะห์ประสิทธิภาพของโปรแกรมที่เขียนด้วยภาษา python เพื่อหา bottleneck หรือปัญหาคอขวดของโปรแกรมของเราว่าอยู่ตรงไหน

Minimum-requirement: Python 2.6 or later [use profiler and pstats package]

ถ้าเครื่องไหนไม่สามารถใช้งานได้ ให้ลงก่อน ด้วยคำสั่งดังกล่าว

$ sudo aptitude install python-profiler

ปกติแล้ว Python profilers จะมี standard library ชื่อว่า profile กับ cProfile ผมแนะนำให้ใช้ cProfile ดีกว่าครับ เพราะค่อนข้าง low-level กว่าและมี overhead ต่ำกว่าด้วยครับ

ตัวอย่างการใช้งานทั่วๆไป

import cProfile
import pstats

def foo():
...

if __name__ == '__main__':
cProfile.run('foo()')

วิธีใช้งานคือ เรียกคำสั่ง cProfile.run(‘ ชื่อฟังก์ชั่น ‘) แค่นั้นเองครับ ง่ายมาก

ตัวอย่างการใช้งานเมื่อมีการส่ง parameter ให้ function

import cProfile
import pstats

def foo(bar):
...

if __name__ == '__main__':
cProfile.run('foo()',[bar])

วิธีใช้งานคือ เรียกคำสั่ง cProfile.run(‘ ชื่อฟังก์ชั่น ‘, list ของ parameter )

ตัวอย่างของผลลัพท์

2706 function calls (2004 primitive calls) in 4.504 CPU seconds

Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)
2 0.006 0.003 0.953 0.477 pobject.py:75(save_objects)
43/3 0.533 0.012 0.749 0.250 pobject.py:99(evaluate)
...

2706 function calls (2004 primitive calls) in 4.504 CPU seconds

หมายถึง มีการเรียก function 2706 ครั้ง ภายในเวลา 4.504 วินาที สำหรับ primitive calls หมายถึง จำนวนการเรียกฟังก์ชั่นแบบไม่ recursive นั่นคือ ถ้ามีการ recursive primitive จะนับแค่ 1 ครั้งเท่านั้น

ncalls หมายถึง จำนวนครั้งที่เรียก function นั้นๆๆ

tottime หมายถึง ปริมาณเวลาทั้งหมด ที่ใช้ในการเรียก function ทั้งหมด

percall หมายถึง สัดส่วน ncall/tottime

cumtime (cumulative time) เวลาที่ใช้ใน function นั้นๆ

percall หมายถึง สัดส่วน primitive call/cumulative time

filename:lineno(function) ระบุ ชื่อไฟล์ บรรทัดที่? และชื่อ function นั้นๆ

สำหรับรายละเอียดเพิ่มเติมสามารถดูได้จาก http://docs.python.org/library/profile.html

ไม่มีความคิดเห็น:

แสดงความคิดเห็น