我有一个我需要读取的文件列表。然而,阅读它们都需要一些时间。我尝试使用线程库,但它似乎没有帮助。
def readFromLog():
#does something with log files
def singleThreadReader(logFiles):
for i in range(len(logFiles)):
readFromLog(logFiles[i])
def multiThreadReader(logFiles):
threads = [threading.Thread(target=readFromLog, args=(log_file,)) for log_file in logFiles]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
比如我有26个文件。 readFromLog() 处理单个文件大约需要 0.3 秒。所以我读完所有 26 个文件大约需要 7.8 (26*0.3) 秒。这是我在调用 singleThreadReader() 时看到的。当我调用 multiThreadReader 时,我也获得了与 singleThreadReader() 相当的执行时间。我确实注意到,如果我取出 thread.joins,时间会减半,但我不认为我想那样做。
我做错了什么?如果我可以同时读取所有 26 个文件,那将是理想的——执行时间总共为 0.3 秒。