Python 多线程不会提高速度

Python multithreading doesn't increase speed

我有 2 个单独的文件,其中包含一个地点的坐标,另一个包含街道和邮政编码。

通过使用 pandas 我想创建一个包含所有三个参数的新 Dataframe,方法是使用唯一键映射它们。问题是时间太长了。

这是通过唯一键映射它们的代码:

def group_comp_with_coord(comp_coord):
    comp_dict = comp_coord[1].to_dict()
    index = comp_coord[0]
    comp_dict.pop('Unnamed: 0', None)
    if index % 10000 == 0:
        print(index)
    comp = companies[(companies.uen == comp_dict['uen'])]
    comp_dict['reg_street_name'] = comp['reg_street_name'].item()
    comp_dict['reg_postal_code'] = comp['reg_postal_code'].item()
    return comp_dict

这是多线程代码:

s = time.time()
test = companies_coordinates.head(100)
pool = ThredPool(5)
company_items = pool.map(group_comp_with_coord, test.iterrows())
pool.close()
pool.join()
df = pd.DataFrame(company_items)
df.to_csv('singapore_companies_coordinates_v2.csv', sep=',', encoding='utf-8')
print('Passed', time.time() - s)

这里的问题是,即使我给 ThreadPool 多少个线程并不重要,它总是会在 6 秒内创建包含 100 行数据的文件。

如何提高速度?

Python 使用 GIL (global interpreter lock),它可以防止多个线程同时执行 Python 字节码。换句话说,一次只执行一个线程,因此在您的情况下几乎不可能实现任何显着的性能提升。

你应该尝试使用Python Multiprocessing Pool代替,它不受GIL限制:

from multiprocessing import Pool

...
pool = Pool(5)
company_items = pool.map(group_comp_with_coord, test.iterrows())
...