Python是一种非常灵活的语言,可以通过多种方式执行单个任务,例如,可以通过多种方式执行初始化列表。但是,这些看似相似的方法之间存在细微的差异。与C ++或Java相比,因其简单性和可读性而广受欢迎的Python同样因其速度慢而臭名昭著。众所周知,“ for”循环速度较慢,而诸如map()和filter()之类的方法由于采用C语言编写,因此速度较快。
# import time module to calculate times import time # initialise lists to save the times forLoopTime = [] whileLoopTime = [] listComprehensionTime = [] starOperatorTime = [] # repeat the process for 500 times # and calculate average of times taken. for k in range(500): # start time start = time.time() # declare empty list a = [] # run a for loop for 10000 times for i in range(10000): a.append(0) # stop time stop = time.time() forLoopTime.append(stop-start) # start time start = time.time() # declare an empty list a = [] i = 0 # run a for loop 10000 times while(i<10000): a.append(0) i+= 1 stop = time.time() whileLoopTime.append(stop-start) start = time.time() # list comprehension to initialize list a = [0 for i in range(10000)] stop = time.time() listComprehensionTime.append(stop-start) start = time.time() # using the * operator a = [0]*10000 stop = time.time() starOperatorTime.append(stop-start) print("Average time taken by for loop: " + str(sum(forLoopTime)/100)) print("Average time taken by while loop: " + str(sum(whileLoopTime)/100)) print("Average time taken by list comprehensions: " + str(sum(listComprehensionTime)/100)) print("Average time taken by * operator: " + str(sum(starOperatorTime)/100))
输出结果
Average time taken by for loop: 0.00623725175858 Average time taken by while loop: 0.00887670278549 Average time taken by list comprehensions: 0.00318484544754 Average time taken by * operator: 0.000371544361115