2016-02-10 60 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

相关问题