python linux 优化_Python 代码性能优化技巧
Python 性能優化除了改進算法,選用合適的數據結構之外,還有幾種關鍵的技術,比如將關鍵 python 代碼部分重寫成 C 擴展模塊,或者選用在性能上更為優化的解釋器等,這些在本文中統稱為優化工具。python 有很多自帶的優化工具,如 Psyco,Pypy,Cython,Pyrex 等,這些優化工具各有千秋,本節選擇幾種進行介紹。
psyco 是一個 just-in-time 的編譯器,它能夠在不改變源代碼的情況下提高一定的性能,Psyco 將操作編譯成有點優化的機器碼,其操作分成三個不同的級別,有"運行時"、"編譯時"和"虛擬時"變量。并根據需要提高和降低變量的級別。運行時變量只是常規 Python 解釋器處理的原始字節碼和對象結構。一旦 Psyco 將操作編譯成機器碼,那么編譯時變量就會在機器寄存器和可直接訪問的內存位置中表示。同時 python 能高速緩存已編譯的機器碼以備今后重用,這樣能節省一點時間。但 Psyco 也有其缺點,其本身運行所占內存較大。目前 psyco 已經不在 python2.7 中支持,而且不再提供維護和更新了,對其感興趣的可以參考 http://psyco.sourceforge.net/
PyPy 表示 "用 Python 實現的 Python",但實際上它是使用一個稱為 RPython 的 Python 子集實現的,能夠將 Python 代碼轉成 C, .NET, Java 等語言和平臺的代碼。PyPy 集成了一種即時 (JIT) 編譯器。和許多編譯器,解釋器不同,它不關心 Python 代碼的詞法分析和語法樹。 因為它是用 Python 語言寫的,所以它直接利用 Python 語言的 Code Object.。 Code Object 是 Python 字節碼的表示,也就是說, PyPy 直接分析 Python 代碼所對應的字節碼 ,,這些字節碼即不是以字符形式也不是以某種二進制格式保存在文件中, 而在 Python 運行環境中。目前版本是 1.8. 支持不同的平臺安裝,windows 上安裝 Pypy 需要先下載 https://bitbucket.org/pypy/pypy/downloads/pypy-1.8-win32.zip,然后解壓到相關的目錄,并將解壓后的路徑添加到環境變量 path 中即可。在命令行運行 pypy,如果出現如下錯誤:"沒有找到 MSVCR100.dll, 因此這個應用程序未能啟動,重新安裝應用程序可能會修復此問題",則還需要在微軟的官網上下載 VS 2010 runtime libraries 解決該問題。具體地址為 http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=5555
安裝成功后在命令行里運行 pypy,輸出結果如下:
C:\Documents and Settings\Administrator>pypy
Python 2.7.2 (0e28b379d8b3, Feb 09 2012, 18:31:47)
[PyPy 1.8.0 with MSC v.1500 32 bit] on win32
Type "help", "copyright", "credits" or "license" for more information.
And now for something completely different: ``PyPy is vast, and contains
multitudes''
>>>>
以清單 5 的循環為例子,使用 python 和 pypy 分別運行,得到的運行結果分別如下:
C:\Documents and Settings\Administrator\ 桌面 \doc\python>pypy loop.py
total run time:
8.42199993134
C:\Documents and Settings\Administrator\ 桌面 \doc\python>python loop.py
total run time:
106.391000032
可見使用 pypy 來編譯和運行程序,其效率大大的提高。
Cython 是用 python 實現的一種語言,可以用來寫 python 擴展,用它寫出來的庫都可以通過 import 來載入,性能上比 python 的快。cython 里可以載入 python 擴展 ( 比如 import math),也可以載入 c 的庫的頭文件 ( 比如 :cdef extern from "math.h"),另外也可以用它來寫 python 代碼。將關鍵部分重寫成 C 擴展模塊
Linux Cpython 的安裝:
第一步:下載
[root@v5254085f259 cpython]# wget -N http://cython.org/release/Cython-0.15.1.zip
--2012-04-16 22:08:35-- http://cython.org/release/Cython-0.15.1.zip
Resolving cython.org... 128.208.160.197
Connecting to cython.org|128.208.160.197|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2200299 (2.1M) [application/zip]
Saving to: `Cython-0.15.1.zip'
100%[======================================>] 2,200,299 1.96M/s in 1.1s
2012-04-16 22:08:37 (1.96 MB/s) - `Cython-0.15.1.zip' saved [2200299/2200299]
第二步:解壓
[root@v5254085f259 cpython]# unzip -o Cython-0.15.1.zip
第三步:安裝
python setup.py install
安裝完成后直接輸入 cython,如果出現如下內容則表明安裝成功。
[root@v5254085f259 Cython-0.15.1]# cython
Cython (http://cython.org) is a compiler for code written in the
Cython language. Cython is based on Pyrex by Greg Ewing.
Usage: cython [options] sourcefile.{pyx,py} ...
Options:
-V, --version Display version number of cython compiler
-l, --create-listing Write error messages to a listing file
-I, --include-dir Search for include files in named directory
(multiple include directories are allowed).
-o, --output-file Specify name of generated C file
-t, --timestamps Only compile newer source files
-f, --force Compile all source files (overrides implied -t)
-q, --quiet Don't print module names in recursive mode
-v, --verbose Be verbose, print file names on multiple compil ation
-p, --embed-positions If specified, the positions in Cython files of each
function definition is embedded in its docstring.
--cleanup
Release interned objects on python exit, for memory debugging.
Level indicates aggressiveness, default 0 releases nothing.
-w, --working
Sets the working directory for Cython (the directory modules are searched from)
--gdb Output debug information for cygdb
-D, --no-docstrings
Strip docstrings from the compiled module.
-a, --annotate
Produce a colorized HTML version of the source.
--line-directives
Produce #line directives pointing to the .pyx source
--cplus
Output a C++ rather than C file.
--embed[=]
Generate a main() function that embeds the Python interpreter.
-2 Compile based on Python-2 syntax and code seman tics.
-3 Compile based on Python-3 syntax and code seman tics.
--fast-fail Abort the compilation on the first error
--warning-error, -Werror Make all warnings into errors
--warning-extra, -Wextra Enable extra warnings
-X, --directive =
[,
Cython 代碼與 python 不同,必須先編譯,編譯一般需要經過兩個階段,將 pyx 文件編譯為 .c 文件,再將 .c 文件編譯為 .so 文件。編譯有多種方法:
通過命令行編譯:
假設有如下測試代碼,使用命令行編譯為 .c 文件。
def sum(int a,int b):
print a+b
[root@v5254085f259 test]# cython sum.pyx
[root@v5254085f259 test]# ls
total 76
4 drwxr-xr-x 2 root root 4096 Apr 17 02:45 .
4 drwxr-xr-x 4 root root 4096 Apr 16 22:20 ..
4 -rw-r--r-- 1 root root 35 Apr 17 02:45 1
60 -rw-r--r-- 1 root root 55169 Apr 17 02:45 sum.c
4 -rw-r--r-- 1 root root 35 Apr 17 02:45 sum.pyx
在 linux 上利用 gcc 編譯為 .so 文件:
[root@v5254085f259 test]# gcc -shared -pthread -fPIC -fwrapv -O2
-Wall -fno-strict-aliasing -I/usr/include/python2.4 -o sum.so sum.c
[root@v5254085f259 test]# ls
total 96
4 drwxr-xr-x 2 root root 4096 Apr 17 02:47 .
4 drwxr-xr-x 4 root root 4096 Apr 16 22:20 ..
4 -rw-r--r-- 1 root root 35 Apr 17 02:45 1
60 -rw-r--r-- 1 root root 55169 Apr 17 02:45 sum.c
4 -rw-r--r-- 1 root root 35 Apr 17 02:45 sum.pyx
20 -rwxr-xr-x 1 root root 20307 Apr 17 02:47 sum.so
使用 distutils 編譯
建立一個 setup.py 的腳本:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension("sum", ["sum.pyx"])]
setup(
name = 'sum app',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
[root@v5254085f259 test]# python setup.py build_ext --inplace
running build_ext
cythoning sum.pyx to sum.c
building 'sum' extension
gcc -pthread -fno-strict-aliasing -fPIC -g -O2 -DNDEBUG -g -fwrapv -O3
-Wall -Wstrict-prototypes -fPIC -I/opt/ActivePython-2.7/include/python2.7
-c sum.c -o build/temp.linux-x86_64-2.7/sum.o
gcc -pthread -shared build/temp.linux-x86_64-2.7/sum.o
-o /root/cpython/test/sum.so
編譯完成之后可以導入到 python 中使用:
[root@v5254085f259 test]# python
ActivePython 2.7.2.5 (ActiveState Software Inc.) based on
Python 2.7.2 (default, Jun 24 2011, 11:24:26)
[GCC 4.0.2 20051125 (Red Hat 4.0.2-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pyximport; pyximport.install()
>>> import sum
>>> sum.sum(1,3)
下面來進行一個簡單的性能比較:
清單 9. Cython 測試代碼
from time import time
def test(int n):
cdef int a =0
cdef int i
for i in xrange(n):
a+= i
return a
t = time()
test(10000000)
print "total run time:"
print time()-t
測試結果:
[GCC 4.0.2 20051125 (Red Hat 4.0.2-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pyximport; pyximport.install()
>>> import ctest
total run time:
0.00714015960693
清單 10. Python 測試代碼
from time import time
def test(n):
a =0;
for i in xrange(n):
a+= i
return a
t = time()
test(10000000)
print "total run time:"
print time()-t
[root@v5254085f259 test]# python test.py
total run time:
0.971596002579
從上述對比可以看到使用 Cython 的速度提高了將近 100 多倍。
本文初步探討了 python 常見的性能優化技巧以及如何借助工具來定位和分析程序的性能瓶頸,并提供了相關可以進行性能優化的工具或語言,希望能夠給相關人員一些參考。
總結
以上是生活随笔為你收集整理的python linux 优化_Python 代码性能优化技巧的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python和matlab交互_MATL
- 下一篇: 李斌:平均每1.9秒就有一辆蔚来从换电站