簡體   English   中英

len() function 是否能夠在 python 上使用 enumerate() 性能來增加 for 循環?

[英]Is it len() function able to increase a for loop using enumerate() performance on python?

在使用 enumerate 的 for 循環之前,您是否已經使用 len() 提高了性能?

我正在經歷這種情況,我不知道為什么會發生這種情況,有人知道嗎? 該代碼從數據庫中獲取一些數據,將其存儲到 arrays data_idsdict_datasend_count 之后,根據第二個數據庫結構准備數據,並以 100 個數據點為一組插入。 如果我刪除調用len(data_ids)len(send_count) ,for 循環的執行會變得非常慢。

data_ids = [0,1,2,3,4,...,2500] #Example of data array
dict_data = [{'a':'0'},{'a':'1'}, {'a':'2'}, ..., {'a':'2'}]  #Example of data array
send_count = [1,3,5,6,7, ..., 0] #Exacly the same len of previous arrays
total = len(dict_data)
prepared_data = []
len(data_ids) #Removing those two, the code gets really slow
len(send_count)

num_to_get = 100
gotten= 0
to_send_data = []

if total <= num_to_get:
    num_to_get = total

for idx, data in enumerate(dict_data):
    print(f'{idx} of {total}\n')

    sent_count = send_count[idx]['send_count']
    data_id = data_ids[idx]['id']

    if sent_count > self.alert_sent_limit:
        print('There are many attempts to send this register without success, '
                            'please review the payload to fix the problem.')
        payload = json.dumps(data)

    prepared_data.append(prepare_data(data['data_object'],data_id))
    gotten = gotten + 1

    if gotten == num_to_get:
        ids_to_update, error_ids = insert_data_on_backend(prepared_data) #Insert data on second database
        ids_to_update = []
        prepared_data = []
        gotten = 0

len沒有副作用,因此從技術上講,調用它不會提高性能。 事實上,如果你調用len並忽略它的返回值,它會稍微降低性能,因為它是死代碼。 這是一些測試:

$ python -m timeit -s 'x = [1, 2, 3]' 'for i, v in enumerate(x): pass'
1000000 loops, best of 3: 0.365 usec per loop
$ python -m timeit -s 'x = [1, 2, 3]; len(x)' 'for i, v in enumerate(x): pass'
1000000 loops, best of 3: 0.39 usec per loop

前者在調用enumerate(x) len(x) x) 而后者調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM