python と cython でリストとハッシュの処理速度を比較をしてみたメモ。
リストの方が速いという結果でしたが、劇的な差があるわけではありませんでした。
リストの方が速いという結果でしたが、劇的な差があるわけではありませんでした。
python_arr: 0.23327970504760742 python_dic: 0.2285747528076172 cython_arr: 0.1210927963256836 cython_dic: 0.17387104034423828
# -*- coding:utf-8 -*- # # array vs hash # import time import test def p_arr(obj): a = obj[0] a = obj[1] a = obj[2] a = obj[3] a = obj[4] return a def p_dic(obj): a = obj['item0'] a = obj['item1'] a = obj['item2'] a = obj['item3'] a = obj['item4'] return a def run(): n = 1000000 arr = [0, 1, 2, 3, 4] dic = {'item0': 0, 'item1': 1, 'item2': 2, 'item3': 3, 'item4': 4} # python arr from_time = time.time() # 実行 for i in range(n): p_arr(arr) to_time = time.time() t = to_time - from_time print("python_arr: %s" % (t)) # python dic from_time = time.time() # 実行 for i in range(n): p_dic(dic) to_time = time.time() t = to_time - from_time print("python_dic: %s" % (t)) # cython arr from_time = time.time() # 実行 for i in range(n): test.c_arr(arr) to_time = time.time() t = to_time - from_time print("cython_arr: %s" % (t)) # cython dic from_time = time.time() # 実行 for i in range(n): test.c_dic(dic) to_time = time.time() t = to_time - from_time print("cython_dic: %s" % (t)) return 0 if __name__ == '__main__': res = run() exit(res)
# -*- coding:utf-8 -*- # cython: language_level=3 # # DEF C_ITEM0 = 0 DEF C_ITEM1 = 1 DEF C_ITEM2 = 2 DEF C_ITEM3 = 3 DEF C_ITEM4 = 4 def c_arr(list obj): #cdef int C_ITEM0 = 0 #cdef int C_ITEM1 = 1 #cdef int C_ITEM2 = 2 #cdef int C_ITEM3 = 3 #cdef int C_ITEM4 = 4 cdef int a a = obj[C_ITEM0] a = obj[C_ITEM1] a = obj[C_ITEM2] a = obj[C_ITEM3] a = obj[C_ITEM4] return a def c_dic(dict obj): cdef int a a = obj['item0'] a = obj['item1'] a = obj['item2'] a = obj['item3'] a = obj['item4'] return a