【问题标题】:Why is my dictionary access so slow?为什么我的字典访问这么慢?
【发布时间】:2016-02-10 05:31:03
【问题描述】:

我正在对 CSV 文件进行一些计算。谁能帮我解释一下为什么方法 1 比方法 2 快 3 倍?我想让我的代码更加通用和可持续,所以我不想像方法 1 那样硬编码,但是一旦我切换到方法 2,性能就会急剧下降,我不知道为什么。

方法一:

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)

方法二:

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

【问题讨论】:

    标签: python csv dictionary


    【解决方案1】:

    你真的需要字典吗?从两个 sn-ps 来看,您似乎只使用了键(或索引 0/1)也许列表会加快速度

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

    这个answer 深入讨论了迭代性能。

    旁注,您是否尝试过来自 itertools 的 product

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

    【讨论】:

    • 感谢您的建议。我已经实现了两者,但性能看起来差不多。 rails_l = ['rail1', 'rail2'] for rail, row in itertools.product(rails_l, itertools.islice(csv_f, 0, period)): 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])
    猜你喜欢
    • 2012-02-13
    • 2021-11-03
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2012-10-17
    相关资源
    最近更新 更多