timeit / cProfile function in Python

timeit 預設是執行程式片段 1,000,000 次,然後取平均時間(秒)

from timeit import timeit
import cProfile


def func1(n):
    array = [str(x * x) for x in xrange(n)]
    return ', '.join(array)


def func2(n):
    array = (str(x * x) for x in xrange(n))
    return ', '.join(array)


print timeit('func1(10)', 'from __main__ import func1')
print timeit('func2(10)', 'from __main__ import func2')

# 不像 timeit,cProfile 並不需要 import
cProfile.run('func1(10)')

ref:
http://www.cnblogs.com/moinmoin/archive/2011/03/18/python-runtime-measuring.html
http://www.codedata.com.tw/python/python-tutorial-the-6th-class-2-performance-pycon-taiwan/