1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| import array import numpy as np def add_list(num): list_a = list([1 for i in range(num)]) list_b = list([1 for i in range(num)]) list_c = list(); for i in range(num): list_c.append(list_a[i]+list_b[i])
def add_array(num): arr_a = array.array('i',[1 for i in range(num)]) arr_b = array.array('i',[1 for i in range(num)]) arr_c = array.array('i') for i in range(len(arr_a)): arr_c.append(arr_a[i]+arr_b[i])
def add_ndarray(num): np_a = np.array([1 for i in range(num)]) np_b = np.array([1 for i in range(num)]) np_c = np_a+np_b
import time ans_list = list() ans_array = list() ans_ndarray = list() def compare_performance(): num = 1 n = 30 for i in range(10): if i >= 6 : n = 3 print(f'=====num=10^{i+1}=====') num*=10 list_start_time = time.time() for j in range(n): add_list(num) list_finish_time = time.time() ans = (list_finish_time-list_start_time)/n*1000 print(f'list用时:{ans}ms') ans_list.append(ans) array_start_time = time.time() for j in range(n): add_array(num) array_finish_time = time.time() ans = (array_finish_time-array_start_time)/n*1000 print(f'array用时:{ans}ms') ans_array.append(ans) ndarray_start_time = time.time() for j in range(n): add_ndarray(num) ndarray_finish_time = time.time() ans = (ndarray_finish_time-ndarray_start_time)/n*1000 print(f'ndarray用时:{ans}ms') ans_ndarray.append(ans) compare_performance()
|