import time deffoo(x,y): tt = time.time() s = 0 for i in range(x,y): s += i print('Time used: {} sec'.format(time.time()-tt)) return s
print(foo(1,100000000))
结果:
Time used: 6.779874801635742 sec 4999999950000000
我们来加一行代码,再看看结果:
from numba import jit import time @jit deffoo(x,y): tt = time.time() s = 0 for i in range(x,y): s += i print('Time used: {} sec'.format(time.time()-tt)) return s print(foo(1,100000000))
结果:
Time used: 0.04680037498474121 sec 4999999950000000
Numba项目的主页上有Linux下的详细安装步骤。编译LLVM需要花一些时间。Windows用户可以从Unofficial Windows Binaries for Python Extension Packages下载安装LLVMPy、meta和numba等几个扩展库。
下面我们看一个例子:
import numba as nb from numba import jit
@jit('f8(f8[:])') defsum1d(array): s = 0.0 n = array.shape[0] for i in range(n): s += array[i] return s
import numpy as np array = np.random.random(10000) %timeit sum1d(array) %timeit np.sum(array) %timeit sum(array) 10000 loops, best of 3: 38.9 us per loop 10000 loops, best of 3: 32.3 us per loop 100 loops, best of 3: 12.4 ms per loop
with open("tmp.py", "w") as f: f.write(""" def square_sum(n): s = 0 for i in range(n): s += i**2 return s """) import py_compile py_compile.compile("tmp.py")
下面调用decompile_pyc将tmp.pyc显示为源代码:
with open("tmp.pyc", "rb") as f: decompile_pyc(f) defsquare_sum(n): s = 0 for i in range(n): s += (i ** 2) return s
from llvm.core import Module, Type, Builder from llvm.ee import ExecutionEngine, GenericValue
# Create a new module with a function implementing this: # # int add(int a, int b) { # return a + b; # } # my_module = Module.new('my_module') ty_int = Type.int() ty_func = Type.function(ty_int, [ty_int, ty_int]) f_add = my_module.add_function(ty_func, "add") f_add.args[0].name = "a" f_add.args[1].name = "b" bb = f_add.append_basic_block("entry")
# Create an execution engine object. This will create a JIT compiler # on platforms that support it, or an interpreter otherwise ee = ExecutionEngine.new(my_module)
# Each argument needs to be passed as a GenericValue object, which is a kind # of variant arg1 = GenericValue.int(ty_int, 100) arg2 = GenericValue.int(ty_int, 42)
# Now let's compile and run! retval = ee.run_function(f_add, [arg1, arg2])
# The return value is also GenericValue. Let's print it. print"returned", retval.as_int() returned 142