擅长:python、mysql、java
<p>在大多数情况下,I/O操作不受CPU的限制,因此使用多个进程是一种过度消耗。使用多个线程是很好的,但是<code>pb.read_csv</code>不仅读取文件,而且解析它,因为它可以是CPU限制的。我建议您在一开始使用asyncio从磁盘读取文件。下面是这样做的代码:</p>
<pre><code>import asyncio
import aiofiles
async def read_file(file_name):
async with aiofiles.open(file_name, mode='rb') as f:
return await f.read()
def read_files_async(file_names: list) -> list:
loop = asyncio.get_event_loop()
return loop.run_until_complete(
asyncio.gather(*[read_file(file_name) for file_name in file_names]))
if __name__ == '__main__':
contents = read_files_async([f'files/file_{i}.csv' for i in range(10)])
print(contents)
</code></pre>
<p>函数<code>read_files_async</code>返回文件内容列表(字节缓冲区),您可以将其传递给<code>pd.read_csv</code>。在</p>
<p>我认为只对文件读取进行优化就足够了,但是你可以用多个进程并行解析文件内容(线程和异步不会提高解析过程的性能):</p>
^{pr2}$
<p>您应该根据您的机器规格设置<code>NUMBER_OF_CORES</code></p>