在前几章,进行了python几种加速的测试。本次进行性能的测试。
测试代码
import timeit
import matx
from python_cython.cython_test import count as cython_count
from python_extern.Extest import count as extern_count
from ctypes import *
def fib(n: int) -> int:
ret :int = 0
for x in range(n + 1):
ret += 1
return ret
def main():
fib_script = matx.script(fib)
ctype_handel = cdll.LoadLibrary("./python_ctypes/count.so")
tmp = c_int(1000000)
print('Matx execution time: %.9fs' % timeit.timeit(lambda: fib_script(1000000), number=10)) # 0.03s
print('cython execution time: %.9fs' % timeit.timeit(lambda: cython_count(1000000), number=10)) # 0.03s
print('extern execution time: %.9fs' % timeit.timeit(lambda: extern_count(1000000), number=10)) # 0.03s
print('ctype execution time: %.9fs' % timeit.timeit(lambda: ctype_handel.count(tmp), number=10)) # 0.03s
#print(fib_script(1000000))
#print(cython_count(1000000))
#print(extern_count(1000000))
#print(ctype_handel.count(tmp))
if __name__ == '__main__':
main()
结果如下:
python3 test.py
Matx execution time: 0.000057373s
cython execution time: 0.000023637s
extern execution time: 0.004334424s
ctype execution time: 0.000057794s
扩展和ctype使用的同样的O2级别优化。但是性能差距超乎意料,反复测试没有找到原因。
测试目录如下
tree ./
./
├── python_ctypes
│ ├── 1.py
│ ├── count.cc
│ └── count.so
├── python_cython
│ ├── 1.py
│ ├── cython_test.c
│ ├── cython_test.cpython-36m-x86_64-linux-gnu.so
│ ├── cython_test.html
│ └── cython_test.pyx
├── python_extern
│ ├── 1.py
│ ├── build
│ │ ├── lib.linux-x86_64-3.6
│ │ └── temp.linux-x86_64-3.6
│ │ └── my_extend.o
│ ├── Extest.cpython-36m-x86_64-linux-gnu.so
│ ├── my_extend.c
│ └── setup.py
└── test.py
6 directories, 14 files