Comparison of the operating efficiency of the 1.while loop and for loop under the same conditions:
The following code:
1 ImportTime as TM2 ImportTimeit as TT3 ImportRandom as RM4 5 defwhile_time ():6i =07 whileI < 100000001:8i + = 19 ifI > 100000:Ten Break One returnI A - - deffor_time (): thej =0 - forIinchRange (100000001): -J + = 1 - ifJ > 100000: + Break - returnJ + A if __name__=="__main__": atT1 = TT. Timer ("for_time ()","From __main__ import for_time") - Print(T1.timeit (number=10)) -t2 = TT. Timer ("while_time ()","From __main__ import while_time") - Print(T2.timeit (number=10))
Results:
Note: As a result above, the time complexity of the for loop and while loop is T (n) =5*n+1, but the for loop is slightly more efficient than the while loop.
2. Efficiency comparisons for traversing lists, tuples, and collections:
The following code:
1 deflist_time ():2 forIinchList1:3i + = 14 5 6 deftuple_time ():7 forIinchTP1:8i + = 19 Ten One defset_time (): A forIinchSet1: -i + = 1 - the defMain (): -List1 = List (range (30000000)) -TP1 =tuple (List1) -Set1 =Set (List1) +T1 = TT. Timer ("list_time ()","From __main__ import list_time") - Print(T1.timeit (number=10)) +t2 = TT. Timer ("tuple_time ()","From __main__ import tuple_time") A Print(T2.timeit (number=10)) atT3 = TT. Timer ("set_time ()","From __main__ import set_time") - Print(T3.timeit (number=10)) - if __name__=="__main__": -Main ()
Results:
Description: The time complexity of the three functions is O (n), the traversal efficiency of the list and the tuple is similar, and the efficiency of the set traversal is slightly lower.
Analysis of data structure running efficiency of Python common use