2016-02-10 59 views
0

我正在對CSV文件進行一些計算。任何人都可以幫我解釋爲什麼方法1比方法2快3倍嗎?我想讓自己的代碼更加通用和可持續,所以我不想像方法1那樣進行硬編碼,但是一旦我切換到方法2,性能就大幅下降,我無法弄清楚原因。爲什麼我的字典訪問速度很慢?

方法1:

for row in itertools.islice(csv_f, 0, period): 
    voltage_rail1 = float(row[rail1_index]) 
    voltage_rail1_q.append(voltage_rail1) 
    current_rail1 = float(row[current_index]) 
    current_rail1_q.append(current_rail1) 
    power_rail1_q.append(voltage_rail1*current_rail1) 

    voltage_rail2 = float(row[rail2_index]) 
    voltage_rail2_q.append(voltage_rail2) 
    current_rail2 = float(row[current_index]) 
    current_rail2_q.append(current_rail2) 
    power_rail2_q.append(voltage_rail2*current_rail2) 

方法2:

rails_d = OrderedDict() 
rails_d['rail1'] = 0 
rails_d['rail2'] = 1 

for row in itertools.islice(csv_f, 0, period): 
    for rail in rails_d: 
     voltage_d[rail] = float(row[voltage_column_index_d[rail]]) 
     voltage_dq[rail].append(voltage_d[rail]) 
     current_d[rail] = float(row[current_column_index_d[rail]]) 
     current_dq[rail].append(current_d[rail]) 
     power_dq[rail].append(voltage_d[rail]*current_d[rail]) 

回答

0

你真的需要一本字典?從這兩個片段,它看起來像你只使用鍵(或索引0/1)也許列表將加快了一點東西

for rail in ['rail1','rail2']: 

answer討論深入的迭代性能。

側面說明,你有沒有從itertools試圖product

for rail, row in itertools.product(['rail1','rail2'], itertools.islice(csv_f, 0, period)): 
+0

感謝您的建議。我已經實現了兩個,但性能看起來差不多。 rail_l = ['rail1','rail2'] for rail,itertools.product(rails_l,itertools.islice(csv_f,0,period))中的行: voltage_d [rail] = float(row [voltage_column_index_d [導軌] current_dq [rail] .append(current_d [導軌]) power_dq [rail]] power_dq [rail] .append(voltage_d [rail]) current_d [rail] = float(row [current_column_index_d [ ] .append(voltage_d [軌] * current_d [軌])' – Colin

相關問題