Posts Tagged ‘optimizing’

[Python] Optimize what needs optimizing?

ปกติแล้ว เวลาผมเขียนโปรแกรมจะถือคตินี้มาตลอด นั่นคือ
Make it done, make it right, and then make it fast.
blog นี้จะมาบอกว่า เราจะ opimize โปรแกรมที่เขียนด้วยภาษา python ได้อย่างไรบ้าง
อย่างแรก ให้ติดตั้ง Python profiler ก่อน คลิก เพื่อดูว่าแต่ละ function ใช้เวลาในการทำงานนานเท่าไหร่
blog นี้ ผมจะสรุปจาก PerformanceTips ละกันครับ

เลือก Data structure ให้เหมาะสม
ใช้ Sorting ของ Python
อ้างอิงจาก Comparing the well-known sorting algorithm ซึ่งผมเคยเทียบประสิทธิภาพไปแล้วว่า python sorting เร็วกว่าใครเพื่อน นอกจากนั้น Guido van Rossum ยังแนะนำให้ใช้ comparator
String Concatenation
หลีกเลี่ยง (เอา string [...]

[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__’:
[...]