Python性能優化 - Life is short, Use python!
Python性能優化 - Life is short, Use python!
性能測試:找出程序的性能瓶頸
要點總結
進階:用C提升Python效率
參考文獻
性能測試:找出程序的性能瓶頸
timeit:python 2.3 新增模組,測少量代碼很方便。
t=timeit.Timer("pattern.match('12345')", "import re; pattern=re.compile('^\d+$')"); print t.repeat(1,1000000)
命令行用法:python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...]
第一個參數是字符串形式的待測代碼段(默認為pass)
第二個參數用以設置代碼的運行環境(如 import XX,默認為pass)
第三個參數可定義計時函數(Windows平臺默認用time.clock(),其他平臺默認使用time.time())
timeit模塊包含一個類Timer,構造函數為:class Timer([stmt='pass' [, setup='pass' [, timer=<timer function>]]])
timeit.Timer有三個成員函數:timeit([number=1000000]);repeat([repeat=3 [, number=1000000]]);print_exc([file=None])
例:
cProfile:python 2.5 新增模組,是profile模組的C實現,與profile接口相同,但更快更準。
例:python -m cProfile myprogram.py
要點總結
賦值
用x, y = y, x,不要用temp = x; x = y; y = temp
正則
不要寫成re.match(pattern, str)、re.search(pattern, str)!!!
雖然Python會自動對最近使用的正則表達式進行cache(cache大小默認為100個),但用compile還是會有明顯的效率提升
需要多次匹配的,先預編譯,再重複使用:pattern = re.compile(pattern_str); pattern.search(str); pattern.match(str)
字符串
例,用isdigit()而不是正則^\d+$,用startswith(str)而不是正則^str
不要用longS = ''; for s in ss: longS += str(s)+'\t',要用longS = '\t'.join([str(s) for s in ss])
少量字符串拼接可用longS = ‘%s\t%s\t%s’ % (s0, s1, s2)
字符串拼接ss = [s0, s1, ..., sN]:
取字符串中的一個片段:s[2:4],s[-1](最後一個字符),s[-2:](最後兩個字符),
字符串匹配查找:能用內置方法的一定用內置方法!!!內置方法比正則效率高很多
歡迎大家關注小編,由於字數有限下一篇繼續更新 list dict function...等等。