并行写入xlsxwriter工作表比顺序写入慢

时间:2018-02-23 04:59:04

标签: multithreading python-3.x parallel-processing xlsxwriter

我想同时写入同一工作簿的多个工作表。 代码如下:

import threading
import xlsxwriter
import time


def write_to_w1(w1, data):
    print('task1 executing....')
    for row, item in enumerate(data):
        w1.write(row, 0, item, row_format)

def write_to_w2(w2, data):
    print('task2 executing....')
    for row, item in enumerate(data):
        w2.write(row, 0, item, row_format)

def write_to_w3(w3, data):
    print('task3 executing....')
    for row, item in enumerate(data):
        w3.write(row, 0, item, row_format)


start = time.time()
data1 = [i for i in range(0,500000)]
data2 = [i for i in range(0,500000)]
data3 = [i for i in range(0,500000)]

workbook = xlsxwriter.Workbook('~/Desktop/threading.xlsx')
row_format = workbook.add_format({'bold': False, 'align': 'left', 'text_wrap': True, 'valign': 'vcenter'})
w1 = workbook.add_worksheet('w1')
w2 = workbook.add_worksheet('w2')
w3 = workbook.add_worksheet('w3')

t1 = threading.Thread(target=write_to_w1, args=(w1, data1), name='t1')
t2 = threading.Thread(target=write_to_w2, args=(w2, data2), name='t2')
t3 = threading.Thread(target=write_to_w3, args=(w3, data3), name='t3')

# starting thread 1
t1.start()
# starting thread 2
t2.start()
# starting thread 3
t3.start()

# wait until thread 1 is completely executed
t1.join()
# wait until thread 2 is completely executed
t2.join()
# wait until thread 3 is completely executed
t3.join()

# both threads completely executed
print("Done!")
workbook.close()
end = time.time()
print('total time ==>', end-start)

在顺序执行基准测试时,并行版本大约需要52秒,顺序版本需要50秒才能执行

导致性能下降的原因是什么?是同步问题还是写入单个工作簿是一个问题?

1 个答案:

答案 0 :(得分:2)

在正常操作中,xlsxwriter将数据存储在内存中,并在close()阶段将数据写入文件然后压缩这些文件。在任何相当大的xlsxwriter程序中,文件写入操作都会占用大部分执行时间。

您没有看到加速的原因可能是由于线程在到达程序的close()部分时已重新加入。

我认为在构造函数中使用{'constant_memory': True}可能会从线程版本获得更好的性能,因为它使用中间文件而不是内存。但是,通过使用您的程序进行快速测试,它没有。

加速大型xlsxwriter程序的更好方法是使用https://www.youtube.com/watch?v=po3wmq4S15A。对于程序的非线程版本,参考系统的执行时间从46.7s(Python2)到8.2s(PyPy)或快近6倍。

实际上pypy的性能接近于xlsxwriter pypy的纯C实现,大约比大型数据集的Python版快10倍。