python常用的数据结构运行效率分析

时间:2022-12-09 23:46:24

1.while循环和for循环相同条件下的运行效率比较:

如下代码:

 1 import time as tm
2 import timeit as tt
3 import random as rm
4
5 def while_time():
6 i = 0
7 while i < 100000001:
8 i += 1
9 if i > 100000:
10 break
11 return i
12
13
14 def for_time():
15 j = 0
16 for i in range(100000001):
17 j += 1
18 if j > 100000:
19 break
20 return j
21
22 if __name__ == "__main__":
23 t1 = tt.Timer("for_time()", "from __main__ import for_time")
24 print(t1.timeit(number=10))
25 t2 = tt.Timer("while_time()", "from __main__ import while_time")
26 print(t2.timeit(number=10))

结果:

python常用的数据结构运行效率分析

说明:如上结果,for循环和while循环的时间复杂度都是T(n)=5*n+1,但是for循环的效率比while循环稍高。

 

2.遍历列表、元组、集合的效率比较:
如下代码:

 1 def list_time():
2 for i in list1:
3 i += 1
4
5
6 def tuple_time():
7 for i in tp1:
8 i += 1
9
10
11 def set_time():
12 for i in set1:
13 i += 1
14
15 def main():
16 list1 = list(range(30000000))
17 tp1 = tuple(list1)
18 set1 = set(list1)
19 t1 = tt.Timer("list_time()", "from __main__ import list_time")
20 print(t1.timeit(number=10))
21 t2 = tt.Timer("tuple_time()", "from __main__ import tuple_time")
22 print(t2.timeit(number=10))
23 t3 = tt.Timer("set_time()", "from __main__ import set_time")
24 print(t3.timeit(number=10))
25 if __name__ == "__main__":
26 main()

结果:

python常用的数据结构运行效率分析
说明:三个函数的查找的时间复杂度都为O(n),列表和元组的遍历效率差不多,集合遍历的效率稍低。