为什么我的词典访问速度如此之慢?

时间:2016-02-10 05:31:03

标签: python csv dictionary

我在CSV文件上运行一些计算。任何人都可以帮我解释为什么方法1比方法2快3倍?我想让我的代码更通用和可持续,所以我不想像方法1那样进行硬编码,但是一旦我切换到方法2并且无法弄清楚原因,性能已大幅下降。

方法1:

SELECT *
FROM prayerrequest
LEFT JOIN encouragements ON prayerrequest.userid = encouragements.userId
WHERE encouragements.userid =27

方法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)

1 个答案:

答案 0 :(得分: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)):