Computer >> Máy Tính >  >> Lập trình >> Python

Python - Cái nào nhanh hơn để khởi tạo danh sách?

Python là một ngôn ngữ rất linh hoạt trong đó một tác vụ đơn lẻ có thể được thực hiện theo một số cách, ví dụ:khởi tạo danh sách có thể được thực hiện theo nhiều cách. Tuy nhiên, có những khác biệt nhỏ trong các phương pháp có vẻ giống nhau này. Python vốn phổ biến vì tính đơn giản và dễ đọc cũng nổi tiếng là chậm chạp so với C ++ hoặc Java. Vòng lặp ‘for’ đặc biệt được cho là chậm trong khi các phương thức như map () và filter () được biết là nhanh hơn vì chúng được viết bằng C.

Ví dụ

# 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))    

Đầu ra

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