
成为
Python
主义者
|
375
先测量一下使用普通的
Python
函数来计算斜边所花费的时间:
>>> import math
>>> from timeit import timeit
>>> from numba import jit
>>>
>>> def hypot(a, b):
... return math.sqrt(a**2 + b**2)
...
>>> timeit('hypot(5, 6)', globals=globals())
0.6349189280000189
>>> timeit('hypot(5, 6)', globals=globals())
0.6348589239999853
使用
@jit
装饰器来进行提速:
>>> @jit
... def hypot_jit(a, b):
... return math.sqrt(a**2 + b**2)
...
>>> timeit('hypot_jit(5, 6)', globals=globals())
0.5396156099999985
>>> timeit('hypot_jit(5, 6)', globals=globals())
0.1534771130000081
使用
@jit(nopython=True)
来避免普通
Python
解释器的开销:
>>> @jit(nopython=True)
... def hypot_jit_nopy(a, b):
... return math.sqrt(a**2 ...