使用Numba加速Python应用
吴江
2018-10-21
1 / 11
题目
打印 11 到 1000 之间,10 进制、2 进制和 8 进制都是回文的数字。
Benchmark: https://github.com/nouse/python-go-simple-benchmark
2 / 11
实现
def is_palindrome(s):
return all(a==b for a,b in itertools.zip_longest(
s, reversed(s)))
def palindrome_number():
for i in CANDIDATES:
if is_palindrome(f'{num:o}') and is_palindrome(
f'{num:b}'):
return -1
3 / 11
第一轮测试
Platform Kops/s
Python 3.7 23.15
PyPy 3.5.3 204.29
Go 1.11.1 746.26
4 / 11
优化:使用整数算法
def palindrome_number2() -> int:
for num in CANDIDATES:
if num == reverse8(num) and num == reverse2(num):
return num
return -1
5 / 11
第二轮测试
Platform Kops/s
Python 3.7 34.10
PyPy 3.5.3 470.56
Go 1.11.1 6211
PyPy 优化不足
6 / 11
Numba
from numba import jit, int32
@jit(int32())
def palindrome_number2() -> int:
for num in CANDIDATES:
if num == reverse8(num) and num == reverse2(num):
return num
return -1
7 / 11
第三轮测试
Platform Kops/s
Python 3.7 34.10
PyPy 3.5.3 470.56
Numba 4769
Go 1.11.1 6211
8 / 11
Numba其他特点
▶ @jitclass
▶ Parallelize
▶ Vectorize
▶ GPU backend(CUDA and AMD HSA)
Homepage: http://numba.pydata.org/
9 / 11
其他工具
Cython https://cython.org/
Pythran https://pythran.readthedocs.io
10 / 11
Thanks!
11 / 11

Python speed up with numba