提高性能有如下方法
1、Cython,用于合并python和c語言靜態(tài)編譯泛型
2、IPython.parallel,用于在本地或者集群上并行執(zhí)行代碼
3、numexpr,用于快速數(shù)值運(yùn)算
4、multiprocessing,python內(nèi)建的并行處理模塊
5、Numba,用于為cpu動態(tài)編譯python代碼
6、NumbaPro,用于為多核cpu和gpu動態(tài)編譯python代碼
為了驗(yàn)證相同算法在上面不同實(shí)現(xiàn)上的的性能差異,我們先定義一個(gè)測試性能的函數(shù)
def perf_comp_data(func_list, data_list, rep=3, number=1): '''Function to compare the performance of different functions. Parameters func_list : list list with function names as strings data_list : list list with data set names as strings rep : int number of repetitions of the whole comparison number : int number ofexecutions for every function ''' from timeit import repeat res_list = {} for name in enumerate(func_list): stmt = name[1] + '(' + data_list[name[0]] + ')' setup = "from __main__ import " + name[1] + ','+ data_list[name[0]] results = repeat(stmt=stmt, setup=setup, repeat=rep, number=number) res_list[name[1]] = sum(results) / rep res_sort = sorted(res_list.items(), key = lambda item : item[1]) for item in res_sort: rel = item[1] / res_sort[0][1] print ('function: ' + item[0] + ', av. time sec: %9.5f, ' % item[1] + 'relative: %6.1f' % rel)
定義執(zhí)行的算法如下
from math import * def f(x): return abs(cos(x)) ** 0.5 + sin(2 + 3 * x)
對應(yīng)的數(shù)學(xué)公式是
生成數(shù)據(jù)如下
i=500000a_py = range(i)
第一個(gè)實(shí)現(xiàn)f1是在內(nèi)部循環(huán)執(zhí)行f函數(shù),然后將每次的計(jì)算結(jié)果添加到列表中,實(shí)現(xiàn)如下
def f1(a): res = [] for x in a: res.append(f(x)) return res
當(dāng)然實(shí)現(xiàn)這種方案的方法不止一種,可以使用迭代器或eval函數(shù),我自己加入了使用生成器和map方法的測試,發(fā)現(xiàn)結(jié)果有明顯差距,不知道是否科學(xué):
迭代器實(shí)現(xiàn)
def f2(a): return [f(x) for x in a]
eval實(shí)現(xiàn)
def f3(a): ex = 'abs(cos(x)) **0.5+ sin(2 + 3 * x)' return [eval(ex) for x in a]
生成器實(shí)現(xiàn)
def f7(a): return (f(x) for x in a)
map實(shí)現(xiàn)
def f8(a): return map(f, a)
接下來是使用numpy的narray結(jié)構(gòu)的幾種實(shí)現(xiàn)
import numpy as np a_np = np.arange(i) def f4(a): return (np.abs(np.cos(a)) ** 0.5 + np.sin(2 + 3 * a))import numexpr as nedef f5(a): ex = 'abs(cos(a)) ** 0.5 + sin( 2 + 3 * a)' ne.set_num_threads(1) return ne.evaluate(ex)def f6(a): ex = 'abs(cos(a)) ** 0.5 + sin(2 + 3 * a)' ne.set_num_threads(2) return ne.evaluate(ex)
新聞熱點(diǎn)
疑難解答
圖片精選